TIL 10: Structs in Go.
Table of Contents
Structs in Go
In Go, it is possible to embed structs within other structs:
type person struct {
first string
last string
age int
}
type employee struct {
person
employee_id int
salary int
}
We can instantiate the employee type as follows:
e := employee{
person: person{
first: "Ali",
last: "Yeşil",
age: 33,
},
employee_id: 001,
salary: 4500,
}
We can then access the fields of the embedded struct as if they were fields of the outer struct:
// e.first is a shorthand for e.person.first
fmt.Println(e.first)
One can also use anonymous structs without explicitly defining a type:
z := struct {
a string
b int
}{
a: "aaa",
b: 123,
}
If these won’t be reused elsewhere, using anonymous structs can keep the code clean.