doujiao1538 2018-04-06 21:56
浏览 356
已采纳

无效的操作:(类型接口{}不支持索引)

I have a function (Load) that creates a map of maps with config for different environments and returns YamlConfig type.

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
}

When I try to use this, however I'm getting the error: invalid operation: host["reader"] (type interface {} does not support indexing)

But host is of type map[string]string

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

fmt.Printf("%T ", host) gives me map[string]string

  • 写回答

1条回答 默认 最新

  • dongzhina7098 2018-04-06 22:04
    关注

    Use a type assertion to get the map[string]string value:

    host, ok := c["production"]["host"].(map[string]string)
    if !ok {
       // handle error
    }
    fmt.Printf("host: %+v: %T
    ", host["reader"], host)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器