Last active
May 21, 2024 14:08
-
-
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.
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" | |
) | |
// 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