Skip to content

Instantly share code, notes, and snippets.

@Tanmay451
Last active May 21, 2024 14:08
Show Gist options
  • Save Tanmay451/69ef947feee5a0010826248119db5e0b to your computer and use it in GitHub Desktop.
Save Tanmay451/69ef947feee5a0010826248119db5e0b to your computer and use it in GitHub Desktop.
Closures are functions that reference variables from outside their body. These variables are captured and remembered even after the outer function has finished executing.
package main
import (
"fmt"
)
// testFunction returns a closure. A closure is a function that captures variables from its surrounding scope.
// In this case, 'y' is captured and maintained between function calls.
func testFunction() func(int) int {
var y int // 'y' is initialized in the enclosing function's scope.
return func(x int) int { // Return an anonymous function that takes an int and returns an int.
y += x // The anonymous function captures and modifies 'y'.
return y // Return the updated value of 'y'.
}
}
func main() {
fFunc := testFunction() // fFunc is a closure returned by testFunction, with its own 'y' variable.
for i := 0; i < 5; i++ {
fmt.Println(fFive(1)) // Each call to fFunc(1) increments 'y' by 1 and prints the result.
}
}
// Output:
// 1
// 2
// 3
// 4
// 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment