EN VI

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

2024-03-14 14:30:04
How to Understanding Go closures calling myinc := inc() vs inc()()

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 ?

Solution:

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.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login