A Go Tour, Exercise: Fibonacci closure

Home   »   A Go Tour, 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 {
	f2, f1 := 0, 1 // f(n) = f(n-1) + f(n-2)
	return func() int {
		f := f2 // f is return value
		f2, f1 = f1, f+f1 
		return f
	}
}

func main() {
	f := fibonacci()
	for i := 0; i < 10; i++ {
		fmt.Println(f())
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *