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() { sum = 0.0 for i := 1; i <= 1e6; i++ { sum += 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):
package main import "fmt" func f() (ret int, str string) { defer func() { ret++ }() defer func() { str += ("##########") }() return 22, "111 " } func main() { fmt.Println(f()) }
Print output:
23 111 ##########
Closure instances:
package main import "FMT" func main () { var F = Adder () fmt. Print (f ( 1), "-" ) fmt. Print (f (), "-" ) fmt. Print (f ( 300 int ) int { 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:
121321