Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
尝试用structs在golang中实现OOPS_Go_Struct - Fatal编程技术网

尝试用structs在golang中实现OOPS

尝试用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)

我试图保留结构的统计信息。我尝试使用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

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

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

递增计数器
需要指针接收器:
(g*Golang)
:)呵呵,它工作了,谢谢。如果您投了反对票,请像真人一样发表评论。