Static local variable in Go
Like Taric' suggestion, but with staticCounter() returning an int function
package main
import (
"fmt"
)
func staticCounter() (f func()(int)){
var i int
f = func()(int){
i++
// fmt.Println(i)
return i
}
return
}
func main() {
f := staticCounter()
g := staticCounter()
fmt.Println(f())
fmt.Println(f())
fmt.Println(f())
fmt.Println(f())
fmt.Println(g())
fmt.Println(g())
}
Declare a var at global scope:
var i = 1
func a() {
println(i)
i++
}
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)
You can do something like this
package main
import (
"fmt"
)
func main() {
f := do()
f() // 1
f() // 2
}
func do() (f func()){
var i int
f = func(){
i++
fmt.Println(i)
}
return
}
Link on Playground https://play.golang.org/p/D9mv9_qKmN