Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I add a field to an existing struct with Go?

Tags:

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.

like image 551
Martin Thoma Avatar asked Mar 12 '15 20:03

Martin Thoma


People also ask

How do I extend a structure in Golang?

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.

How do you assign a value to a struct 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.

Can a struct have functions Golang?

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.

How do you get a struct field in Golang?

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.


1 Answers

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

like image 59
Simon Avatar answered Oct 21 '22 05:10

Simon