You can define methods on structs, allowing you to associate behavior with your data types. To define a method for a struct, you specify a receiver (which can be a value
or a pointer
) in the method definition:
type rect struct {
width int32
height int32
}
func (r rect) area() int {
return r.width * r.height
}
type rect struct {
width int32
height int32
}
func (r *rect) area() int32 {
return r.height * r.width
}
<aside> 💡
If you mutate the value of a struct in a pointer receiver, it is propagated to the final variable (both are referencing the same place in memory)
</aside>