Go Closures
A closure in Go is a function value that captures and references variables from its surrounding lexical scope. This means the inner function maintains a live reference to those variables, allowing it to read and modify them even after the outer function has returned.
Basic Example
Closures enable functions to maintain persistent state across multiple calls, creating "memory" without globals.
Why use Closures?
- State Management: They allow functions to maintain state without using global variables.
- Function Factories: You can create specialized functions on the fly.
- Callbacks: Frequently used in asynchronous code or when passing logic to other functions.
Common Pitfall: Loop Variables
When creating closures inside a loop, they all share the same loop variable if you aren't careful.
To fix this, pass the variable as a parameter or redefine it inside the loop: