douyong4842 2019-08-22 08:07
浏览 37
已采纳

无法将复合文字与map [string] [] struct一起使用[关闭]

I am trying to use composite literal with maps but unable to use it as it shows some error.

please find the code below.

I am a newbie to Golang and perhaps have some less understanding about composite literals.

type Assessment struct{
    StructuringForce map[string][]StructuringForce
}

type StructuringForce struct {
    Principles       map[string][]Capabilities
}

type Capability struct {
}

c1 := Capability{}

a1 := Assessment{

        StructuringForce : map[string][]StructuringForce{
            "Information Systems" , []StructuringForce{
                StructuringForce{
                    Principles : map[string][]Capabilities{
                        "Integration of IT Services" ,[]Capabilities{
                            c1,
                        },
                    },
                },
            },
        },


    }

while constructing "a1" with composite literals I get "Missing key in map literals error".

But i can see that i have added keys.

  • 写回答

1条回答 默认 最新

  • duanmin0941 2019-08-22 08:47
    关注

    As Volker pointed out, make cannot be used with literals. In your case it can either be:

    make(map[string][]StructuringForce)
    

    or

    map[string][]StructuringForce{}{}
    

    Secondly, for golang map, it's using : to separate the key-value, so it should be like:

    a := map[string]string{
      "foo": "bar",
    }
    

    Thirdly, you don't have Capabilities defined, so I suppose you're trying to do Capability.

    To sum up, the entire thing in the main func should look like:

    c1 := Capability{}
    
    a1 := Assessment{
            StructuringForce: map[string][]StructuringForce{
                "Information Systems": []StructuringForce{
                    StructuringForce{
                        Principles: map[string][]Capability{
                            "Integration of IT Services": []Capabilities{
                                c1, // missing comma here as well
                            },
                        },
                    },
                },
            },
        }
    

    However, based on what you pasted, I would suggest you start from something straightforward to get started with the syntax and how to compose a map, like Go By Examples.

    Another suggestion is that you can wrap the running code in main func when posting a SO question, which will make reproducing the issue a lot easier and more understandable to others who try to help.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 虚幻UE引擎如何让多个同一个蓝图的NPC执行一样的动画,
  • ¥15 fluent里模拟降膜反应的UDF编写
  • ¥15 MYSQL 多表拼接link
  • ¥15 关于某款2.13寸墨水屏的问题
  • ¥15 obsidian的中文层级自动编号
  • ¥15 同一个网口一个电脑连接有网,另一个电脑连接没网
  • ¥15 神经网络模型一直不能上GPU
  • ¥15 pyqt怎么把滑块和输入框相互绑定,求解决!
  • ¥20 wpf datagrid单元闪烁效果失灵
  • ¥15 券商软件上市公司信息获取问题