首页 > 解决方案 > 如何向 map[string]interface{} 添加新值

问题描述

我想为map[string]interface{}.

    m := map[string]interface{}{}

    for _, r := range a.RouteSettings {
        m[r.FunctionName] = map[string]interface{}{
            "handler": a.HandlerPath,
            "name":    a.Naming.LambdaFunctionName(r.FunctionName),
            "events": []map[string]interface{}{
                {
                    "http": map[string]interface{}{
                        "path":   r.Path,
                        "method": strings.ToLower(r.Method),
                        "cors":   true,
                    },
                },
            },
        }

        # here is the issue. I want to add new value.
        if a.CognitoArn != "" {
            m[r.FunctionName]["authorizer"] = map[string]interface{}{
                    "arn" : a.CognitoArn,
            }
        }
    }

我希望它的工作结果是这样的:

        m[r.FunctionName] = map[string]interface{}{
            "handler": a.HandlerPath,
            "name":    a.Naming.LambdaFunctionName(r.FunctionName),
            "events": []map[string]interface{}{
                {
                    "http": map[string]interface{}{
                        "path":   r.Path,
                        "method": strings.ToLower(r.Method),
                        "cors":   true,
                    },
                },
            },
            "authorizer" : map[string]interface{}{
                "arn" : a.CognitoArn,   
            },
        }

但它不起作用。
并发生编译错误。

请给出解决方案以增加现有的新价值map[string]interface{}

标签: go

解决方案


因为mis map[string]interface{},你必须断言m[r.FunctionName]的实际类型来做任何有意义的事情:

m[r.FunctionName].(map[string]interface{})["authorizer"] = map[string]interface{}{
        "arn" : a.CognitoArn,
}

但从长远来看,我宁愿花一些时间为这类数据设计结构类型。


推荐阅读