duanlongling5308 2018-10-25 11:32 采纳率: 0%
浏览 42
已采纳

分配嵌入式Struct类型值

Suppose I have the following struct:

type X struct{
    Name string
    Age int
    Email string
}

and then I have 2 other structs (subclasses):

type A struct{
    *X
}

type B struct{
    *X
}

Then in my main code I have:

a := A{&X{"John", 34, "jd@email.com"}}
b := B{&X{"Greg", 22, "gd@email.com"}}
fmt.Println(a.Name) // John
fmt.Println(b.Name) //Greg

Is there a simple way to assign a=b such that a.Name returns Greg as well as all the other properties (I don't want to assign them individually because there's a bunch of properties)

Note: I have to do it this way as I have two identical database tables (in terms of their properties) and the ORM I'm using bases the target table on the struct name. Speaking of, I'm not sure how the ORM identifies the "structure" of the struct to perform this logic, but does using embedded fields, instead of standard fields affect this?

  • 写回答

1条回答 默认 最新

  • dongzhenyin2001 2018-10-25 11:37
    关注

    The unqualified type name acts as the field name when embedding, so you may refer to the embedded value as a.X and b.X.

    You may also assign one to the other:

    a.X = b.X
    fmt.Println(a.Name) // Greg
    fmt.Println(b.Name) // Greg
    

    After this, both will print Greg. Try it on the Go Playground.

    One thing to note here. Since your structs embed a pointer, the above assignment a.X = b.X assigns the pointer value. So after the above modifying fields of one will affect the other.

    So continuing the above example:

    a.X.Name = "Bob"
    fmt.Println(a.Name) // Bob
    fmt.Println(b.Name) // Bob
    

    Both names changed to Bob (try it). If you don't want that, then assign the pointed values, not the pointers:

    *a.X = *b.X
    fmt.Println(a.Name) // Greg
    fmt.Println(b.Name) // Greg
    

    This will again print Greg twice. Try it on the Go Playground.

    And now if you do this:

    a.X.Name = "Bob"
    fmt.Println(a.Name) // Bob
    fmt.Println(b.Name) // Greg
    

    Only a.Name changed, but not b.Name (try it).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题