Trying out go/doc/GoCourseDay1.pdf.
Trying to make sense of:
func adder() (func(int) int) {
My understanding is: declare function adder() with the function literal func(int) as a parameter of type int
In the main function var f = adder() is declared and then called in successive print statements. Why? I tried:
func main() {
fmt.Print(adder(1))
fmt.Print(adder(1))
}
but this fails with the message:
prog.go:15: too many arguments to function call
prog.go:16: too many arguments to function call
Var f = adder() initializes adder() and then calling f you can pass a variable? and this is because func adder() is declared to accept a function literal that accepts an int argument?
In the main function, the line:
ReplyDeletevar f = adder()
can be read as "take the return value of adder() and assign to var f".
In this case, adder() is a function that takes no arguments and returns another function, we'll call "foo". That returned function "foo" is assigned to f.
Take a look at the definition of adder() to see what "foo" is. In this case, adder() sets a variable x which is an int (default value 0), then returns "foo", a function that takes and int and returns an int.
So, the successive print statements of f(1) have a parameter of '1'. That '1' is NOT being passed directly into adder(). Remember, adder() is a function that takes no arguments, which explains why you receive the error message of "prog.go:15: too many arguments to function call".
Rather, the parameter '1' is being passed to the function that is returned by adder(), the "foo" we described earlier on. That "foo" is a closure, which means it pulls in the variables in the context it is called, which pulls the "var x int" from its surrounding adder(). If you recall I mentioned that x has the default value 0, so then f(1) means delta is 1 and x is 0, so x += delta will be 0 + 1 = 1. The closure then returns that '1', and '1' is printed. A key thing to remember is that adder()'s x is now 1, so the next call of f(1) will then call the closure again, this time with delta being 1 and adder()'s x being 1, so 1 + 1 = 2, return, print accordingly.