【问题标题】:Properly initialize a map[string]interface struct正确初始化 map[string]interface 结构
【发布时间】:2021-05-18 13:44:25
【问题描述】:

我有以下结构:

type InstructionSet struct {
    Inst map[string]interface{}
}

Inst 地图中,我想放一些类似的东西

Inst["cmd"] = "dir"
Inst["timeout"] = 10

现在我想直接从代码初始化它,但我没有找到正确的方法

    info := InstructionSet{
        Inst: {
            "command": "dir",
            "timeout": 10,
            },
    }

这样我得到一个错误提示missing type in composite literal。我尝试了一些变化,但我无法获得正确的方法。

【问题讨论】:

    标签: go struct composite-literals


    【解决方案1】:

    错误表示复合文字中缺少类型,因此请提供类型:

    info := InstructionSet{
        Inst: map[string]interface{}{
            "command": "dir",
            "timeout": 10,
        },
    }
    

    Go Playground 上试用。

    【讨论】:

      【解决方案2】:

      复合字面量必须使用字面量的类型来声明:

      info := InstructionSet{
              Inst: map[string]interface{}{
                  "command": "dir",
                  "timeout": 10,
                  },
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-20
        • 1970-01-01
        • 2011-08-20
        • 2023-03-16
        • 2015-01-14
        • 1970-01-01
        相关资源
        最近更新 更多