go的匿名函数

1、go的匿名函数,

//匿名函数,就是函数不带函数名字呢!func(int)(int)
//闭包通过匿名函数实现
func OFFBag() {
    a, str := 10, "闭包"

    //匿名函数定义,形成一个闭包,函数里面可以使用变量a和Str
    f1 := func() { //自动推导
        fmt.Println("a= ", a)
        fmt.Println("str= ", str)
    }

    //调用f1()
    f1()

    //第二种调用方式,少用
    type FuncType func() //定义函数类型
    var f2 FuncType = f1 //声明变量
    f2()

    //第三种调用方式,声明同时调用
    func() { //自动推导
        fmt.Println("a= ", a)
        fmt.Println("str= ", str)
    }() //圆括号代表调用匿名函数

    //带参数的匿名函数
    func(i, j int32) { //自动推导
        fmt.Println("i= ", i)
        fmt.Println("j= ", j)
    }(10, 20) //圆括号代表调用匿名函数

    //有参数有返回值的匿名函数
    max, _ := func(i, j int32) (max, min int32) { //自动推导
        if i > j {
            return i, j
        }
        return j, i
    }(10, 20) //圆括号代表调用匿名函数

    fmt.Println("max= ", max)
}

2、闭包捕获外部变量,他不关心这些捕获的变量或常量是否超出作用域,所以只有闭包还在使用这些变量就会存在

func main() {
    //声明并赋值变量
    str := "闭包的特点"

    fmt.Println("", str)
    f := test1()
    fmt.Println(f())
    fmt.Println(f())
    fmt.Println(f())
    fmt.Println(f())

}

//函数的返回值是一个匿名函数,返回一个函数类型
func test1() func() int32 {
    var x int32
    return func() int32 {
        x++
        return x * x
    }
输出结果:用来初始化一些全局变量

3、

 

posted on 2020-04-01 15:23  HelloOcean  阅读(4478)  评论(0)    收藏  举报

导航