This question already has an answer here:
I have a struct
type keeper struct {
ptr int32
}
then I add a function to it
func(l keeper) next() {
l.ptr++
}
But when I create a new keeper and call next()
tester := keeper {
ptr: 0,
}
test.next()
It seems I am not modifying the ptr value within tester. If I change the function to be a pointer it then works
func(l *keeper) next() {
l.ptr++
}
Why so?
</div>
In Go, a method is just a function that receives an instance of a type. If your function receives an instance as a value, that value is essentially a copy of that instance which will be local to your function and any mutations you make to that instance will not be made to the original instance. If your function receives a pointer to an instance, then any mutations you make will be done directly to the original instance.