小编典典

如何初始化嵌套结构?

go

我不知道如何初始化嵌套结构。在这里找到一个例子:

package main

type Configuration struct {
    Val   string
    Proxy struct {
        Address string
        Port    string
    }
}

func main() {

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

}

阅读 213

收藏
2021-11-09

共1个答案

小编典典

好吧,不让 Proxy 成为自己的结构的任何具体原因?

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

正确的方法,只需将代理移动到它自己的结构体,例如:

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",
    },
}
2021-11-09