嵌套自身的 Struct 该如何实例化?
有个
type A struct { B struct { Count int json:"count" Status int json:"status" } json:"b" }
用 A{B{Count: 112,Status: 112}}报我没有定义 B 请教请教,查了一天资料还没搞定。
有个
type A struct { B struct { Count int json:"count" Status int json:"status" } json:"b" }
用 A{B{Count: 112,Status: 112}}报我没有定义 B 请教请教,查了一天资料还没搞定。
func main() {
a := A{B{
Count: 11,
Status: 10,
}}
fmt.Println(a)
}
我要嵌套自身 Struct,因为需要输出的 json 很复杂,嵌套自身这样看起来很爽
_ := A{
B: struct {
Count int `json:”count”`
Status int `json:”status”`
} {Count: 1, Status: 2},
}
“`
这个玩法并不好,反而更繁琐,如要保持类型的反射匿名可以用 type def
“`go
type X = struct {
Count int `json:”count”`
Status int `json:”status”`
}
“`
B 不是类型名,是字段名
type A 里面的 struct 是一个匿名类型
实例化的时候,需要签名一致,tag 部分也要一样