drryyiuib43562604 2015-03-12 20:45
浏览 234
已采纳

我可以使用Go向现有结构添加字段吗?

Suppose I have the struct

type Planet struct {
    Name       string  `json:"name"`
    Aphelion   float64 `json:"aphelion"`   // in million km
    Perihelion float64 `json:"perihelion"` // in million km
    Axis       int64   `json:"Axis"`       // in km
    Radius     float64 `json:"radius"`
}

as well as instances of this struct, e.g.

var mars = new(Planet)
mars.Name = "Mars"
mars.Aphelion = 249.2
mars.Perihelion = 206.7
mars.Axis = 227939100
mars.Radius = 3389.5

var earth = new(Planet)
earth.Name = "Earth"
earth.Aphelion = 151.930
earth.Perihelion = 147.095
earth.Axis = 149598261
earth.Radius = 6371.0

var venus = new(Planet)
venus.Name = "Venus"
venus.Aphelion = 108.939
venus.Perihelion = 107.477
venus.Axis = 108208000
venus.Radius = 6051.8

Now I want to add a field, e.g. Mass to all of those. How can I do that?

At the moment, I define a new struct, e.g. PlanetWithMass and reassign all fields - field by field - to new instances of the PlanetWithMass.

Is there a less verbose way to do it? A way which does not need adjustment when Planet changes?

edit: I need this on a web server, where I have to send the struct as JSON, but with an additional field. Embedding does not solve this problem as it changes the resulting JSON.

  • 写回答

2条回答 默认 最新

  • duan_88598 2015-03-12 20:48
    关注

    You could embed Planet into PlanetWithMass:

    type PlanetWithMass struct {
        Planet
        Mass float64
    }
    

    and do something like

    marsWithMass := PlanetWithMass{
        Planet: mars,
        Mass: 639e21,
    }
    

    For more info on embedding, see the Spec and Effective Go.

    Playground

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

报告相同问题?

悬赏问题

  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。
  • ¥15 各位 帮我看看如何写代码,打出来的图形要和如下图呈现的一样,急
  • ¥30 c#打开word开启修订并实时显示批注
  • ¥15 如何解决ldsc的这条报错/index error
  • ¥15 VS2022+WDK驱动开发环境
  • ¥30 关于#java#的问题,请各位专家解答!
  • ¥30 vue+element根据数据循环生成多个table,如何实现最后一列 平均分合并
  • ¥20 pcf8563时钟芯片不启振