5.3 Go anonymous function
Go supports anonymous functions, by definition is not the name of the function.
Anonymous function is generally used in the function runs only once, and can make multiple calls.
Anonymous functions can be called the same as ordinary variables.
Anonymous function without the function name 函数声明
and 函数体
composition.
package main import "fmt" func main() { //定义匿名函数,接收2个参数n1,n2,返回值int res := func(n1, n2 int) int { return n1 * n2 }(10, 20) //匿名函数在此处调用,传参 fmt.Println("res=", res) }
Anonymous function assigned to the variable
局部变量
package main import "fmt" func main() { //局部变量n1 n1 := func(a, b int) int { return a * b } fmt.Printf("n1的类型:%T\n", n1) res := n1(10, 10) fmt.Println("res调用结果:", res) }
全局变量
package main import "fmt" //f1就是全局匿名函数 var ( f1 = func(n1, n2 int) int { return n1 * n2 } ) func test() int { return f1(10, 10) } func main() { res := f1(20, 20) fmt.Printf("res结果:%d\n", res) res2 := test() fmt.Printf("res2结果:%d\n", res2) }