在golang中初始化一个嵌套结构中的结构数组。

huangapple go评论78阅读模式
英文:

Initialize an array of structs inside a nested struct in golang

问题

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

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

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

type Cities struct {
    cities []City
}

现在,我该如何初始化这样的结构?如果有人对如何创建这个结构有不同的想法,请告诉我。

谢谢!

英文:

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

答案1

得分: 34

在你的情况下,简写的字面量语法如下:

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)
}
英文:

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:

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:

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)
}

答案2

得分: 6

完整的示例,将所有内容都明确写出来:

state := State{
	id: "独立的Stackoverflow共和国",
	Cities: Cities{
		cities: []City{
			City{
				id: "Postington O.P.",
			},
		},
	},
}
英文:

Full example with everything written out explicitly:

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

huangapple
  • 本文由 发表于 2015年2月12日 21:04:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/28478221.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定