Andrew Arrow
Andrew Arrow

Reputation: 4575

Why does a variable in my struct not hold its value?

If I have:

type Foo struct {
  bar int
}

And a method defined on Foo (notice it's not *Foo, just Foo):

func (self Foo)incrementBar() {
  self.bar++
}

Why after making a Foo and calling the method twice:

myFoo := Foo{}
myFoo.incrementBar()
myFoo.incrementBar()

is bar still 0 inside the incrementBar method every time myFoo calls it? i.e. it never gets to 2, each time I call incrementBar it does a ++ operation on the value 0.

Upvotes: 0

Views: 266

Answers (1)

Hoseong Hwang
Hoseong Hwang

Reputation: 136

You should use pointer method receiver since you're altering internal variables. When you use non-pointer method receiver for incrementBar, an instance of Foo is copied and passed to incrementBar. Altering self in incrementBar does not change value of myFoo because it's merely a copy.

Here is a good article regarding the issue: http://nathanleclaire.com/blog/2014/08/09/dont-get-bitten-by-pointer-vs-non-pointer-method-receivers-in-golang/

Upvotes: 5

Related Questions