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 ?