本文介绍了如何初始化嵌套结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不知道如何初始化嵌套结构.在此处查找示例: http://play.golang.org/p/NL6VXdHrjh
I cannot figure out how to initialize a nested struct. Find an example here:http://play.golang.org/p/NL6VXdHrjh
package main
type Configuration struct {
Val string
Proxy struct {
Address string
Port string
}
}
func main() {
c := &Configuration{
Val: "test",
Proxy: {
Address: "addr",
Port: "80",
}
}
}
推荐答案
那么,是否有不使Proxy成为其自身结构的特定原因?
Well, any specific reason to not make Proxy its own struct?
无论如何,您有2个选择:
Anyway you have 2 options:
正确的方法是,只需将代理移动到其自己的结构中,例如:
The proper way, simply move proxy to its own struct, for example:
type Configuration struct {
Val string
Proxy Proxy
}
type Proxy struct {
Address string
Port string
}
func main() {
c := &Configuration{
Val: "test",
Proxy: Proxy{
Address: "addr",
Port: "port",
},
}
fmt.Println(c)
fmt.Println(c.Proxy.Address)
}
不太恰当和丑陋的方式,但仍然有效:
The less proper and ugly way but still works:
c := &Configuration{
Val: "test",
Proxy: struct {
Address string
Port string
}{
Address: "addr",
Port: "80",
},
}
这篇关于如何初始化嵌套结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!