Golang returning functions
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 identifierf
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 off()
).
makeFunction3
is never assigned to any identifier, and never called.
Let's follow the program flow:
main
starts.main
callsmakeFunction
.makeFunction
prints00000
, and returns an anonymous function.- Back in
main
, we call the anonymous function returned by the previous call. - The anonymous function calls
makeFunction2
. makeFunction2
prints11111
, and returns an anonymous function.main
returns.
Because the return value is discarded after step 6 above, nothing else is printed.
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.