如何在Golang中初始化嵌套结构数组?

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

How to initialize nested structure array in golang?

问题

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

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

有没有一种方法可以在不单独声明Proxy的情况下完成这个操作?

英文:

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?

答案1

得分: 3

你可以这样初始化它:

cfg := Configuration{
	Val: "foo",
	Proxy: []struct {
		Address string
		Port    string
	}{
		{Address: "a", Port: "093"},
	},
}
英文:

You can initialize it as such

cfg := Configuration{
	Val: "foo",
	Proxy: []struct {
		Address string
		Port    string
	}{
		{Address: "a", Port: "093"},
	},
}

答案2

得分: 3

是的,但是由于你必须在某个地方声明类型,所以它看起来有点(主观上)丑陋:

c := Configuration{
	Val: "value",
	Proxy: []struct {
		Address string
		Port    string
	}{
		{"addr1", "2"},
		{"addr2", "4"},
	},
}
英文:

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"},
	},
}

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

发表评论

匿名网友

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

确定