dqsw7529
2015-09-11 20:44
浏览 73
已采纳

如何在Golang中初始化嵌套结构数组? [重复]

This question already has an answer here:

Similar to this question, I'm try to initialize the following structure with some default values:

type Configuration struct {
    Val   string
    Proxy []struct {
        Address string
        Port    string
    }
}

Is there a way to do this without declaring Proxy separately?

</div>

图片转代码服务由CSDN问答提供 功能建议

此问题已经存在 在这里有答案:

  • 初始化嵌套结构 8个答案 \ r

    类似于这个问题,我尝试使用一些默认值初始化以下结构:

      type配置结构{
     Val 字符串
    代理[]结构{
    地址字符串
    端口字符串
    } 
    } 
       
     
     

    有没有一种方法,而无需声明 Proxy 单独?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dpdhnd3577 2015-09-11 20:50
    已采纳

    You can initialize it as such

    cfg := Configuration{
        Val: "foo",
        Proxy: []struct {
            Address string
            Port    string
        }{
            {Address: "a", Port: "093"},
        },
    }
    
    点赞 打赏 评论
  • doutong1890 2015-09-11 20:51

    Yes, but since you have to declare the type somewhere, it gets (subjectively) ugly:

    c := Configuration{
        Val: "value",
        Proxy: []struct {
            Address string
            Port    string
        }{
            {"addr1", "2"},
            {"addr2", "4"},
        },
    }
    
    点赞 打赏 评论

相关推荐 更多相似问题