Go 如何合并2个结构
我正在尝试修改围棋中的一些内容。我创建了以下结构 我有一个API调用,返回如下内容Go 如何合并2个结构,go,Go,我正在尝试修改围棋中的一些内容。我创建了以下结构 我有一个API调用,返回如下内容 MyStruct struct { DID string `bson:"d_id" json:"d_id"` PID string `bson:"p_id" json:"p_id"` ... } 在代码中的一个调用中,我想向该结构追加一个新键 像 问题是,我想添加一个新键,并将其余的保留在对象的根上,就像上面的对象一样。无需重写完整的对
MyStruct struct {
DID string `bson:"d_id" json:"d_id"`
PID string `bson:"p_id" json:"p_id"`
...
}
在代码中的一个调用中,我想向该结构追加一个新键
像
问题是,我想添加一个新键,并将其余的保留在对象的根上,就像上面的对象一样。无需重写完整的对象结构,或对每个键执行for循环
type MyNewStruct struct {
*MyStruct
MyNewKey MyValueType
}
我有,两个变量和数据
MyStructData
和MyNewKeyData
我想,但不知道如何在MyNewStruct
中合并这两个数据,这样MyStructData中的所有内容都将位于键的根,而MyNewKeyData
中的所有内容都将不使用键MyNewKey
我在尝试像这样的东西
theObjectIWant := MyNewStruct {
MyStructData,
"MyNewKey" : MyNewKeyData
}
但不起作用当您在结构中创建匿名成员时,编译器会为该成员生成一个与类型同名的名称。初始化包含结构时,可以使用此名称 下面是一个简化的例子
type MyStruct struct {
DID string
PID string
}
type MyNewStruct struct {
MyStruct
MyNewKey string
}
ms := MyStruct{
DID: "did",
PID: "pid",
}
m := MyNewStruct{
MyStruct: ms,
MyNewKey: "test",
}
我不确定我是否完全理解你在寻找什么,但这可能会有所帮助
type MyStruct struct {
DID string
PID string
}
type myNewStruct struct {
MyStruct
newKey string
}
func main() {
s1 := MyStruct{DID: `bson:"d_id" json:"d_id"`}
s2 := myNewStruct{MyStruct: s1, newKey: `bson:"new_key" json:"new_key"`}
fmt.Println(s2.DID)
fmt.Println(s2.newKey)
}
克里斯·泰勒的答案看起来就像你在寻找的一样。我只想评论一下Golang的术语。您所说的“键”在Golang中被称为“字段”,例如,
DID
&PID
是MyStruct
的字段。不要与“map”中的“key”混淆。不过要小心json封送/解封送!
type MyStruct struct {
DID string
PID string
}
type myNewStruct struct {
MyStruct
newKey string
}
func main() {
s1 := MyStruct{DID: `bson:"d_id" json:"d_id"`}
s2 := myNewStruct{MyStruct: s1, newKey: `bson:"new_key" json:"new_key"`}
fmt.Println(s2.DID)
fmt.Println(s2.newKey)
}