Sahand
Sahand

Reputation: 8370

Why are variables in closure not forgotten?

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?

Upvotes: 0

Views: 103

Answers (1)

John Weldon
John Weldon

Reputation: 40789

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.

Upvotes: 1

Related Questions