微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

golang闭包

http://www.voidcn.com/article/p-hhecpmbx-uo.html
https://www.jianshu.com/p/fa21e6fada70

所谓闭包就是一个函数“捕获”了和它在同一作用于的其他常量和变量。

package main

import "fmt"

func addNumber(x int) func(int) {
    fmt.Printf("x: %d,addr of x:%p\n",x,&x)
    return func(y int) {
        k := x + y
        x = k
        y = k
        fmt.Printf("x: %d,&x)
        fmt.Printf("y: %d,addr of y:%p\n",y,&y)
    }
}

func main() {
    addNum := addNumber(5)
    addNum(1)
    addNum(1)
    addNum(1)

    fmt.Println("---------------------")

    addNum1 := addNumber(5)
    addNum1(1)
    addNum1(1)
    addNum1(1)
}
x: 5,addr of x:0xc4200140c8
x: 6,addr of x:0xc4200140c8
y: 6,addr of y:0xc420014100
x: 7,addr of x:0xc4200140c8
y: 7,addr of y:0xc420014118
x: 8,addr of x:0xc4200140c8
y: 8,addr of y:0xc420014130
---------------------
x: 5,addr of x:0xc420014148
x: 6,addr of x:0xc420014148
y: 6,addr of y:0xc420014158
x: 7,addr of x:0xc420014148
y: 7,addr of y:0xc420014170
x: 8,addr of x:0xc420014148
y: 8,addr of y:0xc420014188

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐