Golang. Why does my local variable saved between call?

Issue

I have a problem with local variable "i". The second time i call nextEven, i think "i" should be intitialized back to 0. But the value "i" is saved in "makeEvengenerator()".

package main

import "fmt"

func makeEvengenerator() func() int {
    i:=0
    return func() (ret int) {
        ret = i
        i += 2
        return ret
    }

}
func main() {
    nextEven := makeEvengenerator()
    fmt.Println(nextEven())
    fmt.Println(nextEven())
    fmt.Println(nextEven())
}

I expected in to print out 0 0 0

Solution

The second time i call nextEven, i think "i" should be intitialized back to 0

Why would it ? If you really want to reinitialize 0, then you can do:

func makeEvengenerator() func() int {
    return func() (ret int) {
        i := 0
        ret = i
        i += 2
        return ret
    }

}

But it would not make much sense as you usually want a closure to encapsulate a state or dependencies.

You can get some documentation and alternate examples here.

Answered By – Ado Ren

Answer Checked By – Mildred Charles (GoLangFix Admin)

Leave a Reply

Your email address will not be published.