5.3 Go 匿名函数

Go支持匿名函数,顾名思义就是没名字的函数。

匿名函数一般用在,函数只运行一次,也可以多次调用。

匿名函数可以像普通变量一样被调用。

匿名函数由不带函数名字的函数声明函数体组成。

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)
}

匿名函数赋值给变量

局部变量

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)
}