Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang returning functions

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!

like image 442
kunrazor Avatar asked Jan 16 '18 21:01

kunrazor


1 Answers

To prints the 3's, you have to call twice:

f()()

And to prints the 4's too, just do:

f()()()

Because ...

// prints "00000" and returns a function that if run
// will invoked `makeFunction2`
f := makeFunction("hello")

// `makeFunction2` is called, printing "11111" and returns 
// a function that if run will invoked `makeFunction3`
f1 := f()

// `makeFunction3` is called, printing "33333" and returns
// a function that if run will invoked `makeFunction4`
f2 := f1()

Test question, what does it print out if you do this?

f := makeFunction("Hello")()()
f()

This is known as currying or closure, but in your example you have not closed over any local value so the latter loses its meaning.

like image 154
Pandemonium Avatar answered Nov 05 '22 14:11

Pandemonium