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 CSS实现渐隐虚线边框
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题