Understand the contract

A closure is a function value that refers to variables from its surrounding lexical scope. Those variables remain available while the closure can use them. This is useful for local callbacks and stateful helpers, but it also means the captured state can change between calls.

newCounter creates a count variable and returns a function that increments it. Each call to newCounter creates separate state. Assigning the returned function to another variable copies the function value while keeping access to the same captured count. A new factory call creates a different counter.

Work through the example

The first counter prints one and two, while the second starts again at one. The returned type func() int describes a function that accepts no arguments and returns an int. You can pass such a value to another function that needs a source of successive numbers.

package main

import "fmt"

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

func main() {
    next := newCounter()
    other := newCounter()
    fmt.Println(next(), next(), other())
}

Watch this boundary

This counter is intended for sequential calls. Calling the same closure from several goroutines introduces shared mutable state and needs synchronization. Also distinguish capturing an existing variable from declaring a new shadowing variable in an inner block: identical names do not always mean identical storage.

Practice with a changed input

Assign alias := next and alternate calls between alias and next. Predict their shared sequence, then create another counter and verify that it starts independently.

References & further reading

Need help with your Go backend?

I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.

Explore Go consulting services