英文:
Editing tags of inherited attributes in golang?
问题
你好!根据你的描述,你想要在Child结构体中编辑json标签,使得Child仍然继承自Parent,但json标签现在变为json:"child_name",对吗?
实际上,Go语言中的结构体字段标签是不可修改的。结构体字段的标签是在编译时确定的,并且无法在运行时进行更改。因此,无法直接编辑Child结构体中继承自Parent的字段的json标签。
不过,你可以通过在Child结构体中重新定义一个与Parent结构体中字段同名但标签不同的字段来实现类似的效果。这样,Child结构体将具有自己的child_name字段,并且仍然可以继承Parent结构体的其他字段和方法。
以下是修改后的代码示例:
type Parent struct {
    Name string `json:"parent_name"`
}
type Child struct {
    Parent
    ChildName string `json:"child_name"`
}
这样,Child结构体将具有一个名为ChildName的字段,并且该字段的json标签为"child_name"。同时,Child结构体仍然继承了Parent结构体的Name字段和相关方法。
希望这可以帮助到你!如果你有任何其他问题,请随时问我。
英文:
type Parent struct {
    Name string `json:"parent_name"`
}
type Child struct {
    Parent
}
Say I have two structs Parent and Child.  I have two endpoints that read json using those two structs.
// Sample Parent endpoint payload
{
    "parent_name": "Parent Name"
}
// Sample Child endpoint payload
{
    "child_name": "Child Name"
}
Both structs are being used to store similar data, but the json key is different for each endpoint payload.  Is there a way to edit the json tag on the Child struct such that Child still inherits from Parent, but the tag is now json:"child_name"?
答案1
得分: 3
Go语言没有继承,只有组合。 不要考虑父子关系,而是考虑部分与整体的关系。
在你的示例中,你可以使用json:"omitempty"标签和"字段遮蔽"的组合来获得结果:
type Parent struct {
    Name string `json:"parent_name,omitempty"`
}
type Child struct {
    Parent
    Name string `json:"child_name"`
}
Playground: http://play.golang.org/p/z72dCKOhYC.
但是这仍然没有解决问题(如果child.Parent.Name不为空会出错)。如果你要在每个嵌入Parent的结构体中"覆盖"一个字段,那么为什么一开始它会存在呢?
英文:
Go doesn't have inheritance, only composition. Instead of parent-child relationship think about it in terms of part-whole.
In your example you can use  a mix of json:",omitempty" tag and "field shadowing" to get the result:
type Parent struct {
	Name string `json:"parent_name,omitempty"`
}
type Child struct {
	Parent
	Name string `json:"child_name"`
}
Playground: http://play.golang.org/p/z72dCKOhYC.
But this still misses the point (and breaks if child.Parent.Name isn't empty). If you're going to "override" a field in every struct that embeds Parent, why is it even there in the first place?
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论