Middle
Mis on sulgemine Go-s
sobes.tech AI
Vastus AI-lt
Closure in Go is a function that "remembers" the values from its surrounding environment, even after the outer function has finished. This allows capturing external variables and using them inside.
// Outer function
func makeCounter() func() int {
count := 0 // Variable to be captured
// Inner function (closure)
return func() int {
count++ // Capture and modify count
return count
}
}
// Usage example
func main() {
counter1 := makeCounter() // Create the first closure
fmt.Println(counter1()) // Output: 1
fmt.Println(counter1()) // Output: 2
counter2 := makeCounter() // Create a second closure (with its own count)
fmt.Println(counter2()) // Output: 1
}