Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static local variable in Go

Tags:

go

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; } 
like image 564
Gustavo Bittencourt Avatar asked May 31 '15 13:05

Gustavo Bittencourt


People also ask

How do you declare a static variable in go?

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.

Where are static local variables stored?

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).


2 Answers

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)

like image 80
IamNaN Avatar answered Sep 20 '22 13:09

IamNaN


Declare a var at global scope:

var i = 1  func a() {   println(i)   i++ } 
like image 20
mjibson Avatar answered Sep 20 '22 13:09

mjibson