Static local variable in Go

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)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)