英文:
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{Income: "404040"},
},
}
错误:无法将 Summary{ Name: "test", Metadata: Clientdata{Income: "404040"} } (类型为 Summary) 用作 []Summary 类型。
我在这里做错了什么?
英文:
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?
答案1
得分: 2
简单来说,你在切片字面量的语法上犯了一个小错误。你的错误在逻辑上是合理的,但可惜它不起作用。
以下是修正后的版本:
v := &important{ client: "xyz", Response: []Summary{
{
Name: "test",
Metadata: Clientdata{ "404040" },
},
},
}
切片字面量的定义如下:
[]type{ items... }
英文:
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... }
答案2
得分: 1
这是要翻译的内容:
不清楚你想如何处理它,因为你的 Response 结构暗示了 []VmSummary 信息,但你却传入了 []Summary。
另外,请查看 https://blog.golang.org/go-slices-usage-and-internals 了解数组的初始化。
像这样?
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"},
},
},
}
}
英文:
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"},
},
},
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论