This is a creation in Article, where the information may have evolved or changed.
An anonymous function cannot exist independently, but can be assigned to a variable, that is, to hold the address of the function into the variable: and fplus := func(x, y int) int { return x + y } then invoke the function through the variable name:fplus(3,4)。
Of course, the anonymous function can also be called directly: func(x, y int) int { return x + y } (3, 4) .
func () { = 0.0 for i: = 1; I <= 1e6; i++ { + = I }} ()
The first pair of parentheses that represent the argument list must be next to the keyword func , because the anonymous function has no name. The curly braces {} cover the function body, and the last pair of parentheses indicate a call to the anonymous function.
Use defer to modify method return values in conjunction with anonymous functions (closures):
"FMT"int, str string) { defer func () { ret+ + } () defer func () { + = ("##########") } ( )return , "111"}func Main () { fmt. Println (f ()) }
Print output:
23 111 ##########
Closure instances:
package mainimport "FMT" func Main () { var F = Adder () fmt. Print (f ( 1), "-" ) fmt. Print (f (), "-" ) fmt. Print (f ( 300))}func Adder () func ( int ) int { var x int return func (Delta int ) int {x += Delta return X}}
The first call to the Adder function returns a func (int) int function, and the value of the local variable x is incremented when re-tuned, and the final output is:
1 + 321