Skip to content

Instantly share code, notes, and snippets.

@himat
Created December 7, 2019 04:34
Show Gist options
  • Save himat/580fcd3934a229de25de5eb650e58efc to your computer and use it in GitHub Desktop.
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
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