What is a closure in Go, and what are common pitfalls when capturing variables in closures?
Last updated
A closure is a function value that captures variables from its surrounding scope by reference, keeping them alive and sharing later mutations.
Pitfalls: pre-Go 1.22 loop closures all saw the final loop value (fix by passing as an argument or
v := v), and goroutines reading captured variables can race.Long-lived closures keep captured variables from being garbage collected.