Search code examples
goanonymous-function

variable lifecycle in anonymous functions golang


im sorry if my question may has obvious or easy answer but i really cant undesrstand what is going on. this is my code:

import "fmt"

func main() {
    a := test()
    a()
    a()
}

func test() func() {
    num := 0
    fmt.Println("num in test function", num)
    return func() {
        fmt.Println("num in anonymous function", num)
        num++
        fmt.Printf("square is %v: \n", num*num)
        fmt.Println("=====---====")
    }
}

and this is my output:

num in test function 0 num in anonymous function 0 square is 1: =====---==== num in anonymous function 1 square is 4: =====---====`

first why println num in test function execute just one time while i execute a() twice? and why num in the anonymous function doesnt reset to zero while the num in parent scope is zero?


Solution

  • When you call a := test() you initialize num variable inside a anonymous fonction and print num in test function 0.

    Then, a is only the result of your test() method, so you will not call your first print when you execute a(). On the same way, num := 0 is not called anymore. So the local variable num assigned inside a will just be incremented on each call of a().