小编典典

初始化嵌套结构

go

我不知道如何初始化嵌套结构。在此处找到示例: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",
        },
    }

}

阅读 270

收藏
2020-07-02

共1个答案

小编典典

好吧,有什么特定的原因不使Proxy成为自己的结构?

无论如何,您有2个选择:

正确的方法是,只需将proxy移至其自己的结构,例如:

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

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

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