尝试在结构中使用golang实现OOPS

问题描述 投票:-2回答:2

我试图保留结构的统计数据。我想要做的是使用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 struct
2个回答
0
投票

当您运行没有指针的方法时,您复制结构数据,当使用poiner时,您更改原始数据。


0
投票

func (g Golang) increaseCounter()改为func (g *Golang) increaseCounter()。您需要指针接收器来更改结构内的数据。

© www.soinside.com 2019 - 2024. All rights reserved.