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
.
Example in C:
int func() {
static int x = 0;
x++;
return x;
}
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
.
Example in C:
int func() {
static int x = 0;
x++;
return x;
}
Declare a var at global scope:
Like Taric' suggestion, but with staticCounter() returning an int function
You can do something like this
Link on Playground https://play.golang.org/p/D9mv9_qKmN
Use a closure:
It doesn't have to be in global scope, just outside the function definition.
(Sample on the Go Playground)
Use Function closure
In following example, variable sum behaves like a separate static for each closure a1 and a2.
Output