Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading