I am trying to retain the stats of a struct. What I am trying to do is create a struct using NewGolang and increase the counter, but all the output are 1. I am expecting 1,2,3. Can somebody please explain.
package main
import "fmt"
type Golang struct {
SessionCounter int
}
func NewGolang() *Golang {
return &Golang{
SessionCounter: 0,
}
}
func (g Golang) increaseCounter() {
g.SessionCounter++
fmt.Println(g.SessionCounter)
}
func main() {
obj := NewGolang()
obj.increaseCounter()
obj.increaseCounter()
obj.increaseCounter()
}
Output:
1
1
1
Expected: 1 2 3
When you run method without pointer you copy struct data, when use poiner you change original data.
Change func (g Golang) increaseCounter()
to func (g *Golang) increaseCounter()
. You need pointer receiver to change the data inside the struct.