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.
We cannot directly extend structs but rather use a concept called composition where the struct is used to form other objects. So, you can say there is No Inheritance Concept in Golang.
Default values can be assigned to a struct by using a constructor function. Rather than creating a structure directly, we can use a constructor to assign custom default values to all or some of its members.
Any real-world entity which has some set of properties or fields can be represented as a struct. As we know that in Go language function is also a user-defined type so, you are allowed to create a function field in the Go structure.
The struct fields are accessed with the dot operator. We create an empty User struct. We initialize the fields with values and read them using the dot operator.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With