Go中的静态局部变量 [英] Static local variable in Go

查看:76
本文介绍了Go中的静态局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在Go中定义一个局部变量,该局部变量可以保持从一个函数调用到另一个函数的值?在C语言中,我们可以使用保留字 static .

Is it possible to define a local variable in Go that can maintain its value from one function call to another? In C, we can do this using the reserved word static.

C语言中的示例:

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

推荐答案

使用闭包:

函数文字是闭包:它们可以引用在中定义的变量周围的功能.然后,这些变量将在周围的函数和函数文字,它们作为只要它们可以访问.

Function literals are closures: they may refer to variables defined in a surrounding function. Those variables are then shared between the surrounding function and the function literal, and they survive as long as they are accessible.

它不必在全局范围内,也不必在函数定义之外.

It doesn't have to be in global scope, just outside the function definition.

func main() {

    x := 1

    y := func() {
        fmt.Println("x:", x)
        x++
    }

    for i := 0; i < 10; i++ {
        y()
    }
}

(在转到操场上的示例)

这篇关于Go中的静态局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆