如何在Go代码中实现C语言的静态变量?

huangapple go评论73阅读模式
英文:

How can I implement C static variable into Go code?

问题

我正在尝试将一段C代码改写为Go,并遇到了一个静态变量。我想知道如何在Go中实现与C中静态变量等效的功能。它是否存在?如果存在,是什么?如果不存在,那么处理这个问题的首选方式是什么?

以下是我想要转换为Go的C代码:

#include <stdio.h>

int func();

int main() {
    printf("%d", func());
    printf("\n%d", func());
    return 0;
}

int func() {
    static int count = 0;
    count++;
    return count;
}

输出:

1
2
英文:

I am trying to re-write a piece of C code into Go and I stumbled upon a static variable. I am wondering how I can achieve the Go's equivalent of C's static variable. Does it exist? If so, what's that? If not, then what would be the preferred way of handling this matter?

Here's the C code that I want to convert into Go:

#include &lt;stdio.h&gt;

int func();

int main() {
    printf(&quot;%d&quot;, func());
    printf(&quot;\n%d&quot;, func());
    return 0;
}

int func() {
    static int count = 0;
    count++;
    return count;
}

Output:

1
2

答案1

得分: 2

你可以使用闭包函数来实现这个功能。

func incrementer() func() int {
    count := 0
    return func() int {
        count++
        return count
    }
}

func main() {
    increment := incrementer()
    fmt.Printf("%d\n", increment())
    fmt.Printf("%d", increment())
}

输出结果:

1
2

你可以在这里了解更多关于闭包的信息:闭包函数

英文:

You can use closure function for that.

func incrementer() func() int {
	count := 0
	return func() int {
		count++
		return count
	}
}

func main() {
	increment := incrementer()
	fmt.Printf(&quot;%d\n&quot;, increment())
	fmt.Printf(&quot;%d&quot;, increment())
}

Output:

1
2

huangapple
  • 本文由 发表于 2022年5月7日 20:00:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/72152272.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定