go - 如何组合 2 个结构内容,一个具有相同的键
问题描述
我有两个结构,一个具有比另一个更多的键,具有更少的键和更多的相同。我想一次给多个键结构提供更少的内容,怎么做?
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 编组和解组仍然会以相同的方式工作
演示
推荐阅读
- java - 为什么这个递归代码无限重复?
- laravel - 无法读取头像图片 mysite.com/storage/app/public/defaults/avatars/user.png 404 错误
- eclipse - 在eclipse中如何创建超类型的覆盖方法?
- python - 实际上 model.save() 在 Keras 中保存了什么?
- android - Kotlin - 传递给 Fragment 时 Activity 中的路径显示为 null 然后更改值
- python - 识别美式日期
- kubernetes - Go 客户端 SDK:检查 Deployment 是否完全就绪
- git - 如何获取Git命令的运行时间?
- c++ - 在 C++ 中为 C 标头中的结构省略“struct”关键字是否安全?
- c++ - WinSock c++ inet_ntop 总是显示 204.204.204.204 (并且 accept() 没有失败)