I have the following struct that has a function that can update its fields:
type Dog struct {
name string
age int
}
func (dog *Dog) growOld() {
dog.name = "old dog"
dog.age++
}
The above works fine on its own. However, when the struct belongs to another object and said object tells the struct to update its fields, the changes seem to occur but do not get applied:
package main
import (
"fmt"
)
type Owner struct {
dog Dog
}
func newOwner(dog Dog) Owner {
var owner Owner
owner.dog = dog
return owner
}
func (owner Owner) tellDogToGrowOld() {
owner.dog.growOld()
}
func main() {
var dog Dog
dog.name = "dog"
owner := newOwner(dog)
owner.tellDogToGrowOld()
fmt.Println(dog) // dog's name is still `dog` and age is 0.
}
I assume I have to use pointers somehow but can't quite figure out how.
tellDogToGrowOldneeds to be defined on a pointer just like you did withgrowOld. Or, alternatively,Owner's dog field needs to be pointer toDog.Owner's dog field should be a pointer toDogapproach because it's the closest to "pass-by-reference" in other languages.