Skip to content

Instantly share code, notes, and snippets.

@sin2akshay
Created May 25, 2018 06:03
Show Gist options
  • Save sin2akshay/bb5267288ef9fe289a9a77def19cd0ef to your computer and use it in GitHub Desktop.
Save sin2akshay/bb5267288ef9fe289a9a77def19cd0ef to your computer and use it in GitHub Desktop.
Tour of Golang | Exercise: Fibonacci closure - https://tour.golang.org/moretypes/26
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
a, b := 0, 1
return func() int {
a, b = b, a+b
//This works because first RHS is computed and stored and then assigned to LHS,
//'a' doesn't changes value before b = a+b
return b - a
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
/*
OUTPUT:
0
1
1
2
3
5
8
13
21
34
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment