0

The following code:

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.

func fibonacci() func() int {
    first, second := 0, 1

    return func() int {
        // return next fibonacci number here.
        first, second = second, first+second
        return  first
    }   
}

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

returns 10 numbers of the fibonacci sequence. What's confusing to me is why is works. It seems like the values first and second are somehow saved in memory, since each time the code is executed, a new fibonacci number in sequence with the previous one is returned. I thought that functions lost their remembered variables when they were done executing. What is going on here?

Sahand
  • 7,980
  • 23
  • 69
  • 137
  • 2
    Well, that's the whole point of a closure. I can recommend reading [this](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work?rq=1) (it's for Javascript, not Go, but that shouldn't really matter here). – tur Mar 30 '16 at 19:48

1 Answers1

1

first, and second are variables in the fibonacci() func, that were 'closed over' by the returned func() int that was returned from fibonacci().

So they are in the closure associated with f, so f has access to those variables as long as it exists.

See this Go Tour slide (and the ones around it) for some explanation of Go closures.

John Weldon
  • 39,849
  • 11
  • 94
  • 127