我无法弄清楚如何初始化嵌套结构.在这里找一个例子: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",
},
}
}
Run Code Online (Sandbox Code Playgroud)
One*_*One 153
那么,任何特定的理由都不能使代理自己的结构?
无论如何,你有2个选择:
正确的方法,只需将代理移动到自己的结构,例如:
type Configuration struct {
Val string
Proxy
}
type Proxy struct {
Address string
Port string
}
func main() {
c := &Configuration{
Val: "test",
Proxy: Proxy{
Address: "addr",
Port: "port",
},
}
fmt.Println(c)
}
Run Code Online (Sandbox Code Playgroud)
不那么正确和丑陋的方式,但仍然有效:
c := &Configuration{
Val: "test",
Proxy: struct {
Address string
Port string
}{
Address: "addr",
Port: "80",
},
}
Run Code Online (Sandbox Code Playgroud)
sep*_*ehr 77
如果您不想为嵌套结构使用单独的结构定义,并且您不喜欢@OneOfOne建议的第二种方法,则可以使用第三种方法:
package main
import "fmt"
type Configuration struct {
Val string
Proxy struct {
Address string
Port string
}
}
func main() {
c := &Configuration{
Val: "test",
}
c.Proxy.Address = `127.0.0.1`
c.Proxy.Port = `8080`
}
Run Code Online (Sandbox Code Playgroud)
你可以在这里查看:https://play.golang.org/p/WoSYCxzCF2
Vit*_*rio 14
Proxy单独定义您的结构,在Configuration此之外,如下所示:
type Proxy struct {
Address string
Port string
}
type Configuration struct {
Val string
P Proxy
}
c := &Configuration{
Val: "test",
P: Proxy{
Address: "addr",
Port: "80",
},
}
Run Code Online (Sandbox Code Playgroud)
见http://play.golang.org/p/7PELCVsQIc
Jos*_*ose 10
你也有这个选项:
type Configuration struct {
Val string
Proxy
}
type Proxy struct {
Address string
Port string
}
func main() {
c := &Configuration{"test", Proxy{"addr", "port"}}
fmt.Println(c)
}
Run Code Online (Sandbox Code Playgroud)
您还可以new手动分配 using和初始化所有字段
package main
type Configuration struct {
Val string
Proxy struct {
Address string
Port string
}
}
func main() {
c := new(Configuration)
c.Val = "test"
c.Proxy.Address = "addr"
c.Proxy.Port = "80"
}
Run Code Online (Sandbox Code Playgroud)
在操场上看到:https : //play.golang.org/p/sFH_-HawO_M
当您想要实例化外部包中定义的公共类型并且该类型嵌入其他私有类型时,就会出现一个问题.
例:
package animals
type otherProps{
Name string
Width int
}
type Duck{
Weight int
otherProps
}
Run Code Online (Sandbox Code Playgroud)
你如何Duck在自己的程序中实例化?这是我能想到的最好的:
package main
import "github.com/someone/animals"
func main(){
var duck animals.Duck
// Can't instantiate a duck with something.Duck{Weight: 2, Name: "Henry"} because `Name` is part of the private type `otherProps`
duck.Weight = 2
duck.Width = 30
duck.Name = "Henry"
}
Run Code Online (Sandbox Code Playgroud)
小智 5
您需要在此期间重新定义未命名的结构 &Configuration{}
package main
import "fmt"
type Configuration struct {
Val string
Proxy struct {
Address string
Port string
}
}
func main() {
c := &Configuration{
Val: "test",
Proxy: struct {
Address string
Port string
}{
Address: "127.0.0.1",
Port: "8080",
},
}
fmt.Println(c)
}
Run Code Online (Sandbox Code Playgroud)
https://play.golang.org/p/Fv5QYylFGAY
| 归档时间: |
|
| 查看次数: |
118184 次 |
| 最近记录: |