doujingke4981 2019-03-15 02:01
浏览 32
已采纳

如何合并2个结构

I am trying to modify some stuff in Go. I have the following struct I created

I have an API call returning something like this

MyStruct struct {
    DID              string `bson:"d_id" json:"d_id"`
    PID              string `bson:"p_id" json:"p_id"`
    ...
}

in one call in the code, I want to append a new key to that struct

like

myNewStruct {
        DID              string `bson:"d_id" json:"d_id"`
        PID              string `bson:"p_id" json:"p_id"`
        ...
        MyNewKey         string `bson:"new_key" json:"new_key"`
}

The thing is, I want to add a new key, and keep the rest at the root of the object, like the object above. without having to rewrite the full object structure, or doing a for loop of each key.

type MyNewStruct struct {
    *MyStruct
    MyNewKey MyValueType
}

I have, two variable with the data,

MyStructData and MyNewKeyData

I want to, but don t know how to merge those two data inside MyNewStruct so that everything in MyStructData will be at the root of the key, and everything in MyNewKeyData will be indise the key MyNewKey

I am trying stuff like

    theObjectIWant := MyNewStruct {
        MyStructData,
        "MyNewKey" : MyNewKeyData 
    }

but doesn't work

  • 写回答

2条回答 默认 最新

  • dongzhimeng2464 2019-03-15 02:29
    关注

    When you create an anonymous member in a struct, the compiler generates a name for the member that is named the same as the type. You can use this name when initializing the containing struct.

    Here is a simplified example

    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",
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 ubuntu系统下挂载磁盘上执行./提示权限不够
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误