What is a Closure?
A closure is a function value that references variables from outside its body. The function can access and modify these variables, and the variables persist between function calls.intSeq returns another function (defined anonymously). The returned function closes over the variable i, forming a closure.
The variable
i is defined in intSeq but persists across multiple calls to the returned function. Each closure maintains its own independent state.Using Closures
When you call a function that returns a closure, the closure captures its own copy of the variables:nextInt() increments and returns its own i variable.
Independent State
Each closure maintains independent state. Creating a new closure creates a new set of variables:Complete Example
Practical Use Cases
Iterators
Configuration
Inline Anonymous Functions
You can also use anonymous functions inline without creating closures:Closures with Goroutines
Closures are commonly used with goroutines, but be careful about variable capture:Advanced Example: Memoization
Closures are perfect for implementing memoization:Best Practices
Use closures for encapsulation
Use closures for encapsulation
Closures provide a way to create private state without defining structs:The
count variable is inaccessible from outside, providing true encapsulation.Be mindful of variable capture
Be mindful of variable capture
Variables captured by closures can lead to unexpected behavior, especially in loops. Always verify what the closure captures.
Consider memory implications
Consider memory implications
Closures keep their captured variables alive, which can prevent garbage collection. For long-lived closures, be mindful of what they capture.
Use closures for callbacks and handlers
Use closures for callbacks and handlers
Closures are ideal for callbacks that need to maintain state:
Key Takeaways
- Closures are anonymous functions that capture variables from their enclosing scope
- Each closure maintains independent state
- Variables captured by closures persist between function calls
- Closures are useful for iterators, configuration, and encapsulation
- Be careful with variable capture in loops and goroutines