可以在Golang中定义一个可以将值从一个函数调用维持到另一个的局部变量吗?在C中,我们可以使用保留字static来实现.
C中的示例:
int func() { static int x = 0; x++; return x; }
使用
closure:
原文链接:https://www.f2er.com/go/186984.htmlFunction 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上的样品)