尝试用structs在golang中实现OOPS
我试图保留结构的统计信息。我尝试使用NewGolang创建一个结构并增加计数器,但是所有的输出都是1。我期待1,2,3。谁能解释一下吗尝试用structs在golang中实现OOPS,go,struct,Go,Struct,我试图保留结构的统计信息。我尝试使用NewGolang创建一个结构并增加计数器,但是所有的输出都是1。我期待1,2,3。谁能解释一下吗 package main import "fmt" type Golang struct { SessionCounter int } func NewGolang() *Golang { return &Golang{ SessionCounter: 0, } } func (g Golang)
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当您运行不带指针的方法时,您复制结构数据,当使用poiner时,您更改原始数据。将
func(g Golang)increaseCounter()
更改为func(g*Golang)increaseCounter()
。您需要指针接收器来更改结构中的数据。递增计数器
需要指针接收器:(g*Golang)
:)呵呵,它工作了,谢谢。如果您投了反对票,请像真人一样发表评论。