What is Closure in Go: Simple Explanation and Example
closure is a function value that references variables from outside its own body. It 'closes over' these variables, keeping their state even after the outer function has finished running.How It Works
Think of a closure like a backpack that a function carries around. This backpack holds variables from the place where the function was created, not just inside the function itself. Even if the original place where those variables lived is gone, the function still has access to them inside its backpack.
In Go, when you create a function inside another function, the inner function can use variables from the outer function. The inner function remembers these variables and can change or use them later. This is useful because it lets the inner function keep track of information between calls, like a counter or a setting.
Example
This example shows a function that returns another function. The returned function remembers the variable count and increases it each time it is called.
package main import "fmt" func counter() func() int { count := 0 return func() int { count++ return count } } func main() { c := counter() fmt.Println(c()) // 1 fmt.Println(c()) // 2 fmt.Println(c()) // 3 }
When to Use
Closures are great when you want to keep some data private but still use it across multiple function calls. For example, you can use closures to create counters, generate unique IDs, or manage state in a clean way without using global variables.
They are also useful in event handling, callbacks, or when you want to customize behavior by creating functions that remember specific settings or data.
Key Points
- A closure is a function that remembers variables from its creation context.
- It allows functions to have private state that persists between calls.
- Closures help avoid global variables and keep code organized.
- They are useful for counters, callbacks, and managing state.