dqnf28092 2019-09-19 00:31
浏览 115
已采纳

如何使用较少的字段将结构转换为其他结构

I am trying to copy a struct of type Big to type Small without explicitly creating a new struct of type Small with the same fields.

I have tried searching for other similar problems such as this and this yet all the conversions between different struct types happen only if the structs have the same fields.

Here is an example of what I tried to do:

// Big has all the fields that Small has including some new ones.
type Big struct {
    A int
    B string
    C float
    D byte
}

type Small struct {
    A int
    B string
}

// This is the current solution which I hope to not use.
func ConvertFromBigToSmall(big Big) Small {
    return Small{
        A: big.A,
        B: big.B,
    }
}

I expected to be able to do something like this, yet it does not work:

big := Big{}
small := Small(big)

Is there a way of converting between Big to Small (and maybe even vice-versa) without using a Convert function?

展开全部

  • 写回答

4条回答 默认 最新

  • dongzhun4898 2019-09-19 00:49
    关注

    There is no built-in support for this. If you really need this, you could write a general function which uses reflection to copy the fields.

    Or you could redesign. If Big is a Small plus some other, additional fields, why not reuse Small in Big?

    type Small struct {
        A int
        B string
    }
    
    type Big struct {
        S Small
        C float
        D byte
    }
    

    Then if you have a Big struct, you also have a Small: Big.S. If you have a Small and you need a Big: Big{S: small}.

    If you worry about losing the convenience of shorter field names, or different marshalled results, then use embedding instead of a named field:

    type Big struct {
        Small // Embedding
        C float
        D byte
    }
    

    Then these are also valid: Big.A, Big.B. But if you need a Small value, you can refer to the embedded field using the unqualified type name as the field name, e.g. Big.Small (see Golang embedded struct type). Similarly, to create a Big from a Small: Big{Small: small}.

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

报告相同问题?

悬赏问题

  • ¥15 没输出运行不了什么问题
  • ¥20 输入import torch显示Intel MKL FATAL ERROR,系统驱动1%,: Cannot load mkl_intel_thread.dll.
  • ¥15 点云密度大则包围盒小
  • ¥15 nginx使用nfs进行服务器的数据共享
  • ¥15 C#i编程中so-ir-192编码的字符集转码UTF8问题
  • ¥15 51嵌入式入门按键小项目
  • ¥30 海外项目,如何降低Google Map接口费用?
  • ¥15 fluentmeshing
  • ¥15 手机/平板的浏览器里如何实现类似荧光笔的效果
  • ¥15 盘古气象大模型调用(python)
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部