Junior — Middle
Explain the mechanism of closure functioning in programming.
sobes.tech AI
Answer from AI
In programming, a closure is a function that "remembers" and can use variables from its outer scope, even if that outer function has already finished executing.
In Go, closures are often created using anonymous functions that access variables from the surrounding context. This allows maintaining state between function calls.
Example:
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
}
Here, the counter function returns a closure that increments and returns the value of count. The variable count is preserved within the closure between calls.