Structs
- Go’s structs are typed collections of fields. They’re useful for grouping data together to form records.
- Go Lang supports Object Oriented Programming Concepts with structs.
- There are no class in Go Lang.
- Structs are mutable.
type person struct {
name string
age int
}
This person struct type has name and age fields.
newPerson constructs a new person struct with the given name. You can safely return a pointer to local variable as a local variable will survive the scope of the function.
func newPerson(name string) *person {
p := person{name: name}
p.age = 42
return &p
}
Access struct fields with a dot.
s := person{name: "Sean", age: 50}
fmt.Println(s.name)
If a struct type is only used for a single value, we don’t have to give it a name. The value can have an anonymous struct type. This technique is commonly used for table-driven tests.
dog := struct {
name string
isGood bool
}{
"Rex",
true,
}
fmt.Println(dog)
Methods
Go supports methods defined on struct types.
This area method has a receiver type of *rect.
type rect struct {
width, height int
}
func (r *rect) area() int {
return r.width * r.height
}
Methods can be defined for either pointer or value receiver types. Here’s an example of a value receiver.
func (r rect) perim() int {
return 2*r.width + 2*r.height
}
Here we call the 2 methods defined for our struct. Go automatically handles conversion between values and pointers for method calls. You may want to use a pointer receiver type to avoid copying on method calls or to allow the method to mutate the receiving struct.
func main() {
r := rect{width: 10, height: 5}
fmt.Println("area: ", r.area())
fmt.Println("perim:", r.perim())
}