'How can I implement C static variable into Go code? [duplicate]

I am trying to re-write a piece of C code into Go and I stumbled upon a static variable. I am wondering how I can achieve the Go's equivalent of C's static variable. Does it exist? If so, what's that? If not, then what would be the preferred way of handling this matter?

Here's the C code that I want to convert into Go:

#include <stdio.h>

int func();

int main() {
    printf("%d", func());
    printf("\n%d", func());
    return 0;
}

int func() {
    static int count = 0;
    count++;
    return count;
}

Output:

1
2


Solution 1:[1]

You can use closure function for that.

func incrementer() func() int {
    count := 0
    return func() int {
        count++
        return count
    }
}

func main() {
    increment := incrementer()
    fmt.Printf("%d\n", increment())
    fmt.Printf("%d", increment())
}

Output:

1
2

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 retiredsloth