在Golang中初始化一个嵌套结构

我无法弄清楚如何初始化一个嵌套的结构。 在这里find一个例子: 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", }, } } 

那么,没有任何具体的原因,使代理自己的结构?

无论如何,你有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) } 

不太正确和丑陋的方式,但仍然有效:

 c := &Configuration{ Val: "test", Proxy: struct { Address string Port string }{ Address: "addr", Port: "80", }, } 

如果你不想使用单独的结构定义嵌套结构,你不喜欢@OneOfOnebuild议的第二种方法,你可以使用第三种方法:

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

你可以在这里查看: https : //play.golang.org/p/WoSYCxzCF2

Configuration之外单独定义您的Proxy结构,如下所示:

 type Proxy struct { Address string Port string } type Configuration struct { Val string P Proxy } c := &Configuration{ Val: "test", P: Proxy{ Address: "addr", Port: "80", }, } 

http://play.golang.org/p/7PELCVsQIc

当你想实例化一个在外部包中定义的公共types时,就会出现一个问题,该typesembedded了其他私有types。

例:

 package animals type otherProps{ Name string Width int } type Duck{ Weight int otherProps } 

你如何在自己的程序中实例化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" } 

你也有这个选项:

 type Configuration struct { Val string Proxy } type Proxy struct { Address string Port string } func main() { c := &Configuration{"test", Proxy{"addr", "port"}} fmt.Println(c) }