json 在 golang 中的嵌套结构中初始化结构数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28478221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:45:42  来源:igfitidea点击:

Initialize an array of structs inside a nested struct in golang

arraysjsongo

提问by mquemazz

I am wondering how can I define and initialize and array of structs inside a nested struct, for example:

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

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

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

type Cities struct {
    cities []City
}

Now how can I Initialize such a structure and if someone has a different idea about how to create the structure itself.

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

Thanks

谢谢

回答by Not_a_Golfer

In your case the shorthand literal syntax would be:

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

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

Or shorter if you don't want the key:value syntax for literals:

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

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

BTW if Cities doesn't contain anything other than the []City, just use a slice of City. This will lead to a somewhat shorter syntax, and remove an unnecessary (possibly) layer:

顺便说一句,如果 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)
}

回答by thwd

Full example with everything written out explicitly:

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

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