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.
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.
You can probably use map[string]string which will enable you to explicitly add as many sub keys as possible. NOTE: You will have to declare the struct first with one type
type PlanetWithMass struct { Planet map[string]string }
Then to add more fields, start by an instance of the struct
type PlanetWithMass struct {
Planet map[string]string
}
planet := &PlanetWithMass{} // instance of struct
planet.Planet = make(map[string]string) // declare field as a map[string]string
planet.Planet["Name"] = "Mercury"
planet.Planet["Galaxy"] = "Milky Way"
planet.Planet["Distance"] = 288888
planet.Planet["Radius"] = 1290
Using this method, you can add several fields to the struct without the worry of using interfaces. It might be a round hack but it works!