我有一个 ??struct Base:
type Base struct {
Name string `json:"name,omitempty"`
// ... other fields
}
Run Code Online (Sandbox Code Playgroud)
还有两个嵌入的结构Base:
type First struct {
Base
// ... other fields
}
type Second struct {
Base
// ... other fields
}
Run Code Online (Sandbox Code Playgroud)
现在我想对结构进行编组First,Second但有一点不同。我想将该Name字段包含在其中,First但我不想将其包含在Second.
或者为了简化这个问题,我想动态地在其 JSON 中选择加入和退出结构的字段。
注意:Name值总是有价值的,我不想改变它。
您可以实现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)
}
Run Code Online (Sandbox Code Playgroud)
这无需对代码进行任何其他更改即可工作。
并且它不会修改中的值,Name因为它适用于不同的类型/副本。
| 归档时间: |
|
| 查看次数: |
1053 次 |
| 最近记录: |