douzhang3898 2016-05-16 03:55
浏览 36
已采纳

将一个结构复制到另一个具有相同成员和不同类型的结构

I have two struct having the same members, I want to copy one struct to another, see the pseudo code below:

type Common struct {
    Gender int
    From   string
    To     string
}

type Foo struct {
    Id    string
    Name  string
    Extra Common
}

type Bar struct {
    Id    string
    Name  string
    Extra Common
}

Then I have foo of struct Foo, and bar of struct Bar, Is there any way to copy bar from foo?

  • 写回答

4条回答 默认 最新

  • dox90448 2016-05-16 04:27
    关注

    Use a conversion. The following code uses a conversion to a copy a value of type Foo to a value of type Bar:

    foo := Foo{Id: "123", Name: "Joe"}
    bar := Bar(foo)
    

    playground example

    The conversion only works when the underlying types are identical except for struct tags.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥30 求给定范围的全体素数p的(p-2)的连乘积
  • ¥15 VFP如何使用阿里TTS实现文字转语音?
  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页