Increment of struct variable in go

I expected to see 3 what is happening?

package main import "fmt" type Counter struct { count int } func (self Counter) currentValue() int { return self.count } func (self Counter) increment() { self.count++ } func main() { counter := Counter{1} counter.increment() counter.increment() fmt.Printf("current value %d", counter.currentValue()) } 

http://play.golang.org/p/r3csfrD53A

+6
source share
1 answer

Your method receiver is the value of the structure, which means that the recipient receives a copy of the structure when called, so it enlarges the copy, and your original is not updated.

To see updates, put your method on the structure pointer.

 func (self *Counter) increment() { self.count++ } 

Now self is a pointer to your counter variable, and so it will update its value.


http://play.golang.org/p/h5dJ3e5YBC

+21
source

Source: https://habr.com/ru/post/945267/


All Articles