【问题标题】:invalid operation: (type interface {} does not support indexing)无效操作:(类型接口{}不支持索引)
【发布时间】:2018-09-16 23:52:46
【问题描述】:

我有一个函数(Load),它为不同的环境创建一个带有配置的地图并返回 YamlConfig 类型。

var config = make(map[string]interface{})

type YamlConfig map[string]map[string]interface{}

type environments struct {
    Test        map[string]interface{}
    Development map[string]interface{}
    Qa          map[string]interface{}
    Staging     map[string]interface{}
    Production  map[string]interface{}
    Brandconsol map[string]interface{}
}

func Load(path string) YamlConfig {
    var config = YamlConfig{}
    var env = environments{}

    data, err := ioutil.ReadFile(path)
    if err != nil {
        errors.Annotate(err, "error reading yaml file")
    }

    err = yaml.Unmarshal(data, &env)
    if err != nil {
        errors.Annotate(err, "error unmarshaling yaml data")
    }

    config = make(map[string]interface{})
    assignToMultiMap(config, env.Production)
    config["production"] = config

    ...

    return config

}

func assignToMultiMap(config map[string]interface{}, converted map[string]interface{}) {
    fmt.Println("converted", converted)
    for k, v := range converted {
        if reflect.TypeOf(v).Kind() == reflect.Map {
            m := make(map[string]string)
            v := v.(map[interface{}]interface{})
            for kk, vv := range v {
                m[kk.(string)] = vv.(string)
            }
            config[strings.ToLower(k)] = m
            continue
        }
        config[strings.ToLower(k)] = parseErb(fmt.Sprintf("%v", v))
    }
}

func parseErb(value string) string {
    if len(value) > 0 {
        re := regexp.MustCompile("<%=\\s+ENV\\['(.+)']\\s+%>")
        match := re.FindStringSubmatch(value)
        if len(match) == 2 {
            value = os.Getenv(match[1])
        }
    }

    return value
}

当我尝试使用它时,我得到了错误:无效操作:主机[“阅读器”](类型接口 {} 不支持索引)

但是主机的类型是map[string]string

c := config.Load("config/database.yml")
host := c["production"]["host"]
fmt.Printf("host: %+v: %T\n", host["reader"], host)

fmt.Printf("%T\n", host) 给我 map[string]string

【问题讨论】:

    标签: go


    【解决方案1】:

    使用type assertion 获取map[string]string 值:

    host, ok := c["production"]["host"].(map[string]string)
    if !ok {
       // handle error
    }
    fmt.Printf("host: %+v: %T\n", host["reader"], host)
    

    【讨论】:

    • 以下错误:invalid type assertion: c["production"].(map[string]&lt;inter&gt;) (non-interface type map[string]interface {} on left)c["production"] 的类型为 map[string]interface {}
    • c["production"]["host"].(map[string]string) 是我所需要的。谢谢!我浏览了该文档几次,但我想它没有深入了解。
    猜你喜欢
    • 2014-10-02
    • 2016-07-27
    • 2018-05-24
    • 1970-01-01
    • 2020-02-12
    • 1970-01-01
    • 2018-10-29
    • 1970-01-01
    • 2013-04-03
    相关资源
    最近更新 更多