dongtan5555 2018-01-12 21:49
浏览 928
已采纳

当一个结构包含另一个结构时,如何在Go中将其转换为另一个结构?

I would like to know if there is easy way to convert from one struct to another in Go when one struct includes the other.

For example

type Type1 struct {
  Field1 int
  Field2 string
}

type Type2 struct {
  Field1 int
}

I know that it can be handled like this

var a Type1{10, "A"}
var b Type2
b.Field1 = a.Field1

but if there are many fields, I will have to write numerous assignments. Is there any other way to handle it without multiple assignments?

In a word, is there anything like b = _.omit(a, 'Field2') in javascript?

  • 写回答

1条回答 默认 最新

  • dongtan8122 2018-01-12 21:53
    关注

    Not directly, no. You can freely convert between identical types only.

    You can get various levels of solutions to this type of problem:

    • writing the assignments out yourself (likely the best performance)
    • using reflection to copy from one to the other based on field names
    • something quick-and-dirty like marshalling one type to JSON then unmarshalling to the other type (which is basically using reflection under the hood with a plaintext middleman, so it's even less efficient, but can be done with little work on your part)
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法