我正在尝试保留结构的统计信息。我想要做的是使用 NewGolang 创建一个结构并增加计数器,但所有输出都是 1。我期待 1、2、3。有人可以解释一下吗。
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()
}
输出:
1
1
1
预期: 1个 2个 3
最佳答案
当你运行没有指针的方法时,你复制了结构数据,当你使用指针时,你改变了原始数据。
关于go - 尝试使用结构在 golang 中实现 OOPS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49987028/