Golang returning functions

kunrazor :

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!

Pierre Prinetti :

Let's look at your main:

Line 1

f := makeFunction("hellooo")
  • Side effect: printing "00000"
  • Return value: an anonymous function that executes makeFunction2("abcef"), assigned to the identifier f

Line 2

f()

which is equivalent to:

_ = f()
  • Side effect: printing "11111"
  • Return value: an anonymous function that executes makeFunction3("safsf"), discarded (you are not assigning the return value of f()).

makeFunction3 is never assigned to any identifier, and never called.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related