Go Closures
A closure is a function that "closes over" variables from its surrounding scope. This means the function can remember and access these variables even after the outer function has finished executing.
Basic Example
Closures are often used to create functions with "memory" or state.
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: