go / intermediate
Snippet
Encapsulating state within closures
A closure is a function value that references variables from outside its body. In Go, returning a function that references a local variable binds the variable to that instance of the function, creating encapsulated state without using explicit struct objects.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package mainimport "fmt"func newCounter() func() int {count := 0return func() int {count++return count}}func main() {counter := newCounter()fmt.Println(counter())fmt.Println(counter())anotherCounter := newCounter()fmt.Println(anotherCounter())}
Breakdown
1
func newCounter() func() int {
Defines a higher-order function that returns another function returning an int.
2
count := 0
Declares a local variable whose scope is extended because it is captured by the returned closure.
3
return func() int {
Returns the anonymous inner function (closure) that modifies and reads the outer variable.