Skip to content

Instantly share code, notes, and snippets.

@mkwatson
Created September 27, 2024 14:23
Show Gist options
  • Save mkwatson/d79a8f4643e4de8b76bd99d548cf2604 to your computer and use it in GitHub Desktop.
Save mkwatson/d79a8f4643e4de8b76bd99d548cf2604 to your computer and use it in GitHub Desktop.
package main
import "fmt"
// outerFunction returns a closure (an inner function) that captures and uses the variable 'x'
func outerFunction(x int) func(int) int {
// The inner function, which forms a closure
return func(y int) int {
return x + y // 'x' is captured from outerFunction's scope
}
}
func main() {
// Create a closure by calling outerFunction with 'x' set to 5
closure := outerFunction(5)
// Call the closure with different values of 'y'
fmt.Println(closure(3)) // Output: 8
fmt.Println(closure(7)) // Output: 12
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment