在Golang中初始化嵌套结构 [英] Initialize a nested struct in Golang

查看:876
本文介绍了在Golang中初始化嵌套结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚如何初始化一个嵌套的结构体。在此处查找示例:
http://play.golang.org/p/NL6VXdHrjh

 包主

类型配置结构{
Val字符串
代理结构{
地址字符串
端口字符串
}
}

func main(){

c:=& Configuration {
Val:test,
代理服务器:{
地址:addr,
端口:80,
},
}



解决方案

代理自己的结构?



无论如何,你有2个选择:
$ b 正确的方法是,简单地将代理移动到它的结构自己的结构,例如:

  type配置struct {
Val字符串
代理
}

类型代理struct {
地址字符串
端口字符串
}

func main(){

c:=& Configuration {
Val:test,
Proxy:Proxy {
Address:addr,
Port:port,


fmt.Println(c)
}




$ b $

  c:=& Configuration {
Val: test,
代理:struct {
地址字符串
端口字符串
} {
地址:addr,
端口:80,
},
}


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",
        },
    }

}

解决方案

Well, any specific reason to not make Proxy its own struct?

Anyway you have 2 options:

The proper way, simply move proxy to its own struct, for example:

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

The less proper and ugly way but still works:

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

这篇关于在Golang中初始化嵌套结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆