Closures in Go
A function value captures the variables it uses, not their values.
func counter(start int) func() int {
count := start
return func() int {
count++
return count
}
}
func adders() []int {
var funcs []func() int
for i := 1; i <= 3; i++ {
funcs = append(funcs, func() int { return i * 10 })
}
var out []int
for _, f := range funcs {
out = append(out, f())
}
return out
}
How it works
- Each call to the outer function gets its own captured state.
- Returning a closure is how Go writes a counter or a generator.
- Since Go 1.22 each loop iteration has its own variable.
Keywords and builtins used here
appendforfuncintrangereturnvar
The run, in numbers
- Lines
- 20
- Characters to type
- 301
- Tokens
- 99
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 66 seconds.
Step 3 of 6 in Functions, step 12 of 30 in Language basics.