[英]How to initialize nested struct in 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... //错误:无法使用摘要{名称:“ test”,元数据:Clientdata {“ 404040”},}(类型摘要)作为类型[]摘要更多...
What I am doing wrong here? 我在这里做错了什么?
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... }
It wasn't clear how you wanted to approach it, as your Response struct implies []VmSummary info, but you are feeding it []Summary. 由于您的Response结构隐含[] VmSummary信息,目前尚不清楚您想如何使用它,但您正在提供[] Summary。
Also, check https://blog.golang.org/go-slices-usage-and-internals on initialization of arrays. 另外,请检查https://blog.golang.org/go-slices-usage-and-internals有关数组初始化的信息。
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"},
},
},
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.