Home > other >  New learner Golang. Why does my local variable saved between call?
New learner Golang. Why does my local variable saved between call?

Time:11-11

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 Also I dont understand why everytime I call nextEven(), the code "i:=0" dont run again everytime i call the nextEven()

CodePudding user response:

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.

  • Related