我可以使用Go向现有结构添加字段吗? [英] Can I add a field to an existing struct with Go?
问题描述
假设我有结构
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
现在我想添加一个字段,例如 Mass
都可以.我该怎么办?
Now I want to add a field, e.g. Mass
to all of those. How can I do that?
此刻,我定义了一个新的结构,例如 PlanetWithMass
,然后将所有字段(逐字段)重新分配给 PlanetWithMass
的新实例.
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:我需要在Web服务器上使用它,在这里我必须将结构以JSON格式发送,但要有一个附加字段.嵌入无法解决此问题,因为它会更改生成的JSON.
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.
推荐答案
您可以将 Planet
嵌入到 PlanetWithMass
中:
type PlanetWithMass struct {
Planet
Mass float64
}
做类似的事情
marsWithMass := PlanetWithMass{
Planet: mars,
Mass: 639e21,
}
有关嵌入的更多信息,请参见规范和
For more info on embedding, see the Spec and Effective Go.
➜游乐场
这篇关于我可以使用Go向现有结构添加字段吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!