我有一个结构Base
:
type Base struct {
Name string `json:"name,omitempty"`
// ... other fields
}
还有两个嵌入Base
的结构:
type First struct {
Base
// ... other fields
}
type Second struct {
Base
// ... other fields
}
现在我想要对结构First
和Second
进行元素化,但稍有不同。我想在Name
中加入First
字段,但我不想将其包含在Second
中。
或者为了简化问题,我想动态选择加入JSON中的结构字段。
注意:
Name
值始终具有价值,我不想更改它。
答案 0 :(得分:3)
您可以为类型Marshaler
实现Second
接口,并创建虚拟类型SecondClone
。
type SecondClone Second
func (str Second) MarshalJSON() (byt []byte, err error) {
var temp SecondClone
temp = SecondClone(str)
temp.Base.Name = ""
return json.Marshal(temp)
}
这将不会对您的代码进行任何其他更改。
它不会修改Name
中的值,因为它适用于不同的类型/副本。
答案 1 :(得分:-1)
尝试这样的事情:
type Base struct {
Name string `json: "name,omitempty"`
// ... other fields
}
type First struct {
Base
// ... other fields
}
type Second struct {
Base
Name string `json: "-"`
// ... other fields
}
这意味着您不能再在代码中调用Second.Base.Name,而只能调用Second.Name。