Created
September 27, 2024 14:23
-
-
Save mkwatson/d79a8f4643e4de8b76bd99d548cf2604 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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