如何在 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"},
}
}]

//错误:无法使用摘要{名称:"测试",元数据:客户端数据{"404040"},}(摘要类型(作为类型[]摘要更多...

我在这里做错了什么?

简单地说,你稍微搞砸了切片文字的语法。你的错误是相当合乎逻辑的,但可悲的是它不起作用。

以下是固定版本:

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

切片文本的定义如下:

[]type{ items... }

目前尚不清楚您希望如何处理它,因为您的响应结构意味着 []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"},
},
},
}
}

最新更新