Understanding Go closures calling myinc := inc() vs inc()()

53 Views Asked by At

I am learning go and working on closures. I am slightly confused by the following;

func inc() func() int {
    var i int = 0
    return func() int {
        i++
        return i
    }
}

func main() {
    myinc := inc()
    fmt.Println(myinc())
    fmt.Println(myinc())
    fmt.Println(myinc())
}

This code results in printing 1, 2, 3 as expected. What I am confused by is it is my understanding that calling myinc() is essentially the same as calling inc()(). If I do the following:

func main() {
    fmt.Println(inc()())
    fmt.Println(inc()())
    fmt.Println(inc()())
}

I get a result of 1, 1, 1.

Am I misunderstanding what is happening in myinc := inc() vs inc()() ? Could someone please explain to me what is happening here ?

1

There are 1 best solutions below

1
N.F. On BEST ANSWER

var i int = 0 is executed when you call inc().

In your first code, inc() is called only once at myinc := inc(). In second code, inc() is called three times.