dongliu6848 2017-07-28 02:12
浏览 276
已采纳

如何在Golang中初始化嵌套结构?

type important struct {
client     string                 `json:"client"`
Response   Summary        `json:"response"`

}

type Summary struct {
Name     string           `json:"name"`
Metadata Clientdata      `json:"metadata"`
}

type Clientdata struct {
Income string           `json:"income"` 
}


v := &important{ client: "xyz", Response:  Summary[{
            Name: "test",
            Metadata: Clientdata { "404040"},
        }
    }]

//Error: Cannot use Summary{ Name: "test", Metadata: Clientdata { "404040"}, } (type Summary) as type []Summary more...

What I am doing wrong here?

  • 写回答

2条回答 默认 最新

  • douzhanrun0497 2017-07-28 02:19
    关注

    To put it simply, you goofed the syntax of a slice literal slightly. Your mistake is fairly logical, but sadly it doesn't work.

    The following is a fixed version:

    v := &important{ client: "xyz", Response: []Summary{
            {
                Name: "test",
                Metadata: Clientdata { "404040"},
            },
        },
    }
    

    A slice literal is defined like so:

    []type{ items... }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • duanqing3026 2017-07-28 02:26
    关注

    It wasn't clear how you wanted to approach it, as your Response struct implies []VmSummary info, but you are feeding it []Summary.

    Also, check https://blog.golang.org/go-slices-usage-and-internals on initialization of arrays.

    Something like that?

    type important struct {
        client   string    `json:"client"`
        Response []Summary `json:"response"`
    }
    
    type Summary struct {
        Name     string     `json:"name"`
        Metadata Clientdata `json:"metadata"`
    }
    
    type Clientdata struct {
        Income string `json:"income"`
    }
    
    func main() {
        v := &important{
            client: "xyz",
            Response: []Summary{
                {
                    Name:     "test",
                    Metadata: Clientdata{"404040"},
                },
            },
        }
    }
    
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于网上一个easyx制作的见缝插针小游戏(c++)
  • ¥15 开地址法双散列函数处理碰撞
  • ¥15 想问一下这个是什么情况 虚拟机Linux打不开了
  • ¥15 联通光猫掉注册了怎么重新注册上去
  • ¥15 关于unity开发steamvr程序遇到的问题
  • ¥60 求tc downloader的下载方式
  • ¥15 华为 快捷方式 手电筒 接口
  • ¥15 Qt6.5支不支持Android13开发啊
  • ¥20 网络只能跑一半,应该如何设置
  • ¥20 Python调用百度开发者平台人脸识别接口