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

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

问题描述

是否可以在Golang中定义一个局部变量,它可以从一个函数调用保持其值不变?在C中,我们可以使用保留字 static

Is it possible to define a local variable in Golang 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;
}


推荐答案

使用封闭


函数文字是闭包:它们可能会引用
a周围函数中定义的变量。这些变量然后在
的周围函数和函数文字之间共享,并且它们可以以
的长度存活,因为它们可以访问。

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 Playground

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

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