【问题标题】:Initialize an array of structs inside a nested struct in golang在golang中初始化嵌套结构内的结构数组
【发布时间】:2015-04-13 05:35:35
【问题描述】:

我想知道如何在嵌套结构中定义和初始化结构数组,例如:

type State struct {
    id string `json:"id" bson:"id"`
    Cities 
}

type City struct {
    id string `json:"id" bson:"id"`
}

type Cities struct {
    cities []City
}

现在我该如何初始化这样的结构,如果有人对如何创建结构本身有不同的想法。

谢谢

【问题讨论】:

    标签: arrays json go


    【解决方案1】:

    在您的情况下,速记文字语法是:

    state := State {
        id: "CA",
        Cities:  Cities{
            []City {
                {"SF"},
            },
        },
    }
    

    如果您不想要文字的键:值语法,或者更短:

    state := State {
        "CA", Cities{
            []City {
                {"SF"},
            },
        },
    }    
    

    顺便说一句,如果 Cities 不包含除 []City 以外的任何内容,则只需使用 City 的一部分。这将导致语法更短,并删除不必要的(可能)层:

    type State struct {
        id string `json:"id" bson:"id"`
        Cities []City
    }
    
    type City struct {
        id string `json:"id" bson:"id"`
    }
    
    
    func main(){
        state := State {
            id: "CA",
            Cities:  []City{
                 {"SF"},
            },
        }
    
        fmt.Println(state)
    }
    

    【讨论】:

    • 完美,我想直到我对 Go 中的嵌入和嵌套结构还不够习惯,毕竟处理 java 这么多年,这对我来说是全新的,但非常感谢 :D
    【解决方案2】:

    明确写出所有内容的完整示例:

    state := State{
        id: "Independent Republic of Stackoverflow",
        Cities: Cities{
            cities: []City{
                City{
                    id: "Postington O.P.",
                },
            },
        },
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多