type Parent struct {
Name string `json:"parent_name"`
}
type Child struct {
Parent
}
说我有两个结构Parent
和Child
。我有两个端点使用这两个结构读取json
。
// Sample Parent endpoint payload
{
"parent_name": "Parent Name"
}
// Sample Child endpoint payload
{
"child_name": "Child Name"
}
两个结构都用于存储类似的数据,但每个端点有效负载的json
密钥不同。有没有办法编辑json
结构上的Child
标记,Child
仍然继承自Parent
,但标记现在是json:"child_name"
?
答案 0 :(得分:3)
Go没有继承,只有组合。而不是父子关系从部分整体的角度思考。
在您的示例中,您可以混合使用json:",omitempty"
标记和"字段阴影"得到结果:
type Parent struct {
Name string `json:"parent_name,omitempty"`
}
type Child struct {
Parent
Name string `json:"child_name"`
}
游乐场:http://play.golang.org/p/z72dCKOhYC。
但这仍然忽略了这一点(如果child.Parent.Name
不是空的,则会中断)。如果你要去"覆盖"嵌入Parent
的每个结构中的一个字段,为什么它首先就在那里呢?