英文:
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"},
},
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论