Go Structs
Links: 103 Golang Index
Structs¶
- Struct is a sequence of named elements, called fields.
- Each of them has a name and a type.
- If you are familiar with OOP from other languages you can think of a struct as of a class.
- The struct fields are like the instance attributes we define in OOP.
- Unlike traditional Object-Oriented Programming, Go does not have a class-object architecture.
- Rather we have structs which hold complex data structures.
- A structs is nothing more that a schema containing a blueprint of data a structure will hold.
- This blueprint is fixed at compile time.
- It's not allowed to change the name or the type of the fields at runtime.
- You can't add or remove fields from a struct at runtime.
Creating Structs¶
- In the below example order matters
- Above is not the recommended way to initialise structs
- If we create a struct by omitting some values of fields, they will be assigned default values.
- We can also create a struct with the default value of its types
Retrieving and updating fields¶
- To retrieve fields and update we use the
.
operator
Comparison of Structs¶
- We can compare structs using
==
sign - For 2 structs to be equal all the fields must have the same value
Creating a copy¶
- We can use
=
or:=
to create a copy.- This is contrary to what happens in maps and slices
Anonymous Structs¶
- In the above example we have created a book3 struct without defining a struct type alias - This is useful when we don't want to reuse a struct type - Anonymous fields - We can mix anonymous fields with named fieldsEmbedded Structs¶
- An embedded struct is just a struct that acts like field in another struct
- The advantage is that embedded structs can also be used as standalone structs
type address struct { city, country string } type employee struct { name string newAddress address } emp1 := employee{ name: "Sarthak", newAddress: address{ city: "abc", country: "dde", }, // important since we are declaring multiline structs } fmt.Println(emp1.newAddress.city) // abc fmt.Printf("%+v", emp1) // {name:Sarthak newAddress:{city:abc country:dde}}
Miscellaneous¶
type person struct {
name string
age int
colors []string
}
me := person{
name: "Marius",
age: 30,
colors: []string{"red", "yellow"},
}
Last updated: 2022-06-18