You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go语言用结构体实现OOP时计数器无法累加的问题求助

Why Your Go Struct Counter Isn't Incrementing Correctly

Hey there! I see the issue right away—let's break this down simply.

The problem comes down to how your increaseCounter method interacts with your struct instance. Right now, you're using a value receiver (g Golang) for the method:

func (g Golang) increaseCounter() {
    g.SessionCounter++
    fmt.Println(g.SessionCounter)
}

In Go, when you use a value receiver, every time you call the method, Go creates a full copy of your struct. That means when you increment g.SessionCounter, you're only modifying this temporary copy—not the original obj you created in main(). The original struct's SessionCounter stays stuck at 0, so every call makes a new copy, increments it to 1, and prints that number.

The Fix: Switch to a Pointer Receiver

To modify the original struct's state (and keep your counter incrementing properly), you need to use a pointer receiver (*Golang). This tells Go to pass a reference to your original struct instance instead of making a copy:

func (g *Golang) increaseCounter() {
    g.SessionCounter++
    fmt.Println(g.SessionCounter)
}

With this change, every call to increaseCounter will operate directly on the original obj you created. Now when you run your code, you'll get the expected output: 1, 2, 3.

Here's the full corrected code for reference:

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()
}

A quick rule of thumb: if your method needs to change the state of a struct, always use a pointer receiver. Value receivers are perfect for methods that only read data from the struct without modifying it!

内容的提问来源于stack exchange,提问作者James Sapam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:08:40