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; }
Static Type Declaration in Go A static type variable declaration provides assurance to the compiler that there is one variable available with the given type and name so that the compiler can proceed for further compilation without requiring the complete detail of the variable.
The static variables are stored in the data segment of the memory. The data segment is a part of the virtual address space of a program. All the static variables that do not have an explicit initialization or are initialized to zero are stored in the uninitialized data segment( also known as the BSS segment).
Use a 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.
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() } }
(Sample on the Go Playground)
Declare a var at global scope:
var i = 1 func a() { println(i) i++ }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With