Created
December 7, 2019 04:34
-
-
Save himat/580fcd3934a229de25de5eb650e58efc to your computer and use it in GitHub Desktop.
[Using closures to maintain state] Nice abstraction to add closures instead of having to maintain separate state variables within the main body #golang
This file contains 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
import "fmt" | |
func adder() func(int) int { | |
sum := 0 | |
return func(x int) int { | |
sum += x | |
return sum | |
} | |
} | |
func main() { | |
pos, neg := adder(), adder() | |
for i := 0; i < 10; i++ { | |
fmt.Println( | |
pos(i), | |
neg(-2*i), | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment