加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

golang中的静态局部变量

发布时间:2020-12-16 19:20:30 所属栏目:大数据 来源:网络整理
导读:可以在Golang中定义一个可以将值从一个函数调用维持到另一个的局部变量吗?在C中,我们可以使用保留字static来实现. C中的示例: int func() { static int x = 0; x++; return x;} 使用 closure: Function literals are closures: they may refer to variabl
可以在Golang中定义一个可以将值从一个函数调用维持到另一个的局部变量吗?在C中,我们可以使用保留字static来实现.

C中的示例:

int func() {
    static int x = 0; 
    x++;
    return x;
}
使用 closure:

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.

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

func main() {

    x := 1

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

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

(Go Playground上的样品)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读