Golang returning functions

kunrazor picture kunrazor · Jan 16, 2018 · Viewed 15.8k times · Source

Can anyone explain why 0's and 1's are printed and not anything else? Thank you!

func makeFunction(name string) func() {
    fmt.Println("00000")
    return func() {
        makeFunction2("abcef")
    }
}

func makeFunction2(name string) func() {
    fmt.Println("11111")
    return func() {
        makeFunction3("safsf")
    }
}

func makeFunction3(name string) func() {
    fmt.Println("33333")
    return func() {
        fmt.Printf("444444")
    }
}

func main() {
    f := makeFunction("hellooo")
    f()
}

Can anyone explain why 0's and 1's are printed and not anything else? Thank you!

Answer

Adrian picture Adrian · Jan 16, 2018

Let's follow the program flow:

  1. main starts.
  2. main calls makeFunction.
  3. makeFunction prints 00000, and returns an anonymous function.
  4. Back in main, we call the anonymous function returned by the previous call.
  5. The anonymous function calls makeFunction2.
  6. makeFunction2 prints 11111, and returns an anonymous function.
  7. main returns.

Because the return value is discarded after step 6 above, nothing else is printed.