go闭包

作者: 明明就_c565 | 来源:发表于2019-12-27 18:40 被阅读0次

    闭包简单的说就是一个匿名函数+外部变量的引用,举例如下

    示例一

    package main

    import (

        "fmt"

    )

    func appendStr() func(string) string {

        t := "Hello"

        c := func(b string) string {

            t = t + " " + b

            return t

        } 

        return c

    }

    func add(base int) func(int) int {

        fmt.Printf("%p\n", &base) //打印变量地址,可以看出来 内部函数时对外部传入参数的引用

        f := func(i int) int {

            fmt.Printf("%p\n", &base)

            base += i

            return base

        } 

        return f

    }

    func main() {

        a := appendStr()

        b := appendStr()

        fmt.Println(a("World"))

        fmt.Println(b("Everyone"))

        fmt.Println(a("Gopher"))

        fmt.Println(b("!"))

        t1 := add(10)

        fmt.Println(t1(1), t1(2))

        t2 := add(100)

        fmt.Println(t2(1), t2(2))

    }

    运行结果

    Hello World

    Hello Everyone

    Hello World Gopher

    Hello Everyone !

    0xc000014100

    0xc000014100

    0xc000014100

    11 13

    0xc000014118

    0xc000014118

    0xc000014118

    101 103

    示例二

    package main

    import (

        "fmt"

    )

    func main() {

        x, y := 1, 2

        defer func(a int) {

            fmt.Println("defer x, y = ", a, y) //y为闭包引用

        }(x) //x值拷贝 调用时传入参数

        x += 100

        y += 200

        fmt.Println(x, y)

    }

    运行结果

    101 202

    defer x, y =  1 202

    示例三

    package main

    import (

        "fmt"

    )

    //返回加减函数,重点:内部函数时对外部变量的引用

    func calc(base int) (func(int) int, func(int) int) {

        fmt.Printf("%p\n", &base)

        add := func(i int) int {

            fmt.Printf("%p\n", &base)

            base += i

            return base

        } 

        sub := func(i int) int {

            fmt.Printf("%p\n", &base)

            base -= i

            return base

        } 

        return add, sub

    }

    //由 main 函数作为程序入口点启动

    func main() {

        f1, f2 := calc(100)

        fmt.Println(f1(1), f2(2)) //执行顺序:f1 f2 println

        fmt.Println(f1(3), f2(4))

        fmt.Println(f1(5), f2(6))

        fmt.Println(f1(7), f2(8))

    }

    运行结果

    0xc0000a4000

    0xc0000a4000

    0xc0000a4000

    101 99

    0xc0000a4000

    0xc0000a4000

    102 98

    0xc0000a4000

    0xc0000a4000

    103 97

    0xc0000a4000

    0xc0000a4000

    104 96

    相关文章

      网友评论

          本文标题:go闭包

          本文链接:https://www.haomeiwen.com/subject/kzgdoctx.html