Go中的静态局部变量

是否可以在 Go 中定义一个局部变量,该变量可以从一个函数调用到另一个函数保持其值?在 C 中,我们可以使用保留字来做到这一点static。


C 中的示例:


int func() {

    static int x = 0; 

    x++;

    return x;

}


jeck猫
浏览 364回答 3
3回答

泛舟湖上清波郎朗

使用闭包:函数字面量是闭包:它们可以引用在周围函数中定义的变量。然后这些变量在周围的函数和函数文字之间共享,只要它们可以访问,它们就会存在。它不必在全局范围内,就在函数定义之外。func main() {&nbsp; &nbsp; x := 1&nbsp; &nbsp; y := func() {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("x:", x)&nbsp; &nbsp; &nbsp; &nbsp; x++&nbsp; &nbsp; }&nbsp; &nbsp; for i := 0; i < 10; i++ {&nbsp; &nbsp; &nbsp; &nbsp; y()&nbsp; &nbsp; }}(Go Playground示例)

动漫人物

在全局范围内声明一个 var:var i = 1func a() {&nbsp; println(i)&nbsp; i++}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go