dai
9/23/2010 - 8:56 PM

fib-closure.go

package main

// fib returns a function that returns
// successive Fibonacci numbers.
// quoted by golamg.org
func fib() func() int {
  a, b := 0,1
  return func() int {
    a, b = b, a+b
    return b
  }
}

func main() {
  f := fib()
  // Function calls are evaluated left-to-right.
  println(f(), f(), f(), f())
}