我有两个结构,一个比另一个有更多的键,键更少但更相同。我想同时为多个键结构提供更少的内容,怎么办?
type moreStruct struct {
A string `json:"a"`
B string `json:"b"`
C string `json:"c"`
D string `json:"d"`
E string `json:"e"`
}
type leseStruct struct {
A string `json:"a"`
B string `json:"b"`
D string `json:"d"`
}
more := moreStruct{
A: "aaa",
B: "bbb",
C: "ccc",
D: "ddd",
E: "eee",
}
less := leseStruct{
A: "aaaaaaa",
B: "bbbbbbb",
D: "ddddddd",
}
//hava any better mothod than below in one line
more.A = less.A
more.B = less.B
more.D = less.D
最佳答案
是的,如果您可以更改类型/结构本身,则可以使用嵌入,这样您就可以重新分配整个字段子集。这确实意味着您必须稍微更改编写文字的方式,并且由于您使用的是 json,因此需要导出嵌入类型。
// Less, the smallest subset of fields that are shared
type Less struct {
A string `json:"a"`
B string `json:"b"`
D string `json:"d"`
}
// More the type that has all the fields in Less + some of its own
type More struct {
Less // embed Less in this type
C string `json:"c"`
E string `json:"e"`
}
现在我们已经有了这些类型,这就是用文字初始化字段的方式:
more := More{
Less: Less{
A: "aaa",
B: "bbb",
D: "ddd",
},
C: "ccc",
E: "eee",
}
// or the dirty way (no field names) - don't do this... it's nasty
yuck := More{
Less{
"a",
"b",
"d",
},
"c",
"e",
}
现在,假设我们有一个像这样的变量 less
:
less := Less{
A: "aaaaa",
B: "bbbbb",
D: "ddddd",
}
现在我们要将这些值复制到我们在上面创建的变量 more
中:
more.Less = less
工作完成...因为嵌入了 Less
类型,所以 json 编码和解码仍将以相同的方式工作
Demo
关于go - 如何组合 2 个结构内容,一个具有相同的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56159489/