0

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?

WhatABeautifulWorld
  • 3,198
  • 3
  • 22
  • 30
  • See another related Q&A: [https://stackoverflow.com/questions/27775376/value-receiver-vs-pointer-receiver-in-golang](https://stackoverflow.com/questions/27775376/value-receiver-vs-pointer-receiver-in-golang) – putu Jun 29 '17 at 15:05

1 Answers1

0

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.

Joshua Jones
  • 1,364
  • 1
  • 9
  • 15