Skip to content

Instantly share code, notes, and snippets.

@EduardoVaca
Created July 1, 2015 17:25
Show Gist options
  • Save EduardoVaca/d831268a3376b6b7513c to your computer and use it in GitHub Desktop.
Save EduardoVaca/d831268a3376b6b7513c to your computer and use it in GitHub Desktop.
/*Go functions may be closures. A closure is a function value that references variables from outside its body.
The function may access and assign to the referenced variables; in this sense the function is "bound" to the variables.
Implement a fibonacci function that returns a function (a closure) that returns successive fibonacci numbers.*/
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
fib := 0
prev := 0
auxFib := 0
return func() int{
if fib == 0{
fib = 1
}else{
auxFib = fib
fib += prev
prev = auxFib
}
return fib
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
/*output
1
1
2
3
5
8
13
21
34
55
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment