码迷,mamicode.com
首页 > 其他好文 > 详细

golang闭包

时间:2018-09-13 14:17:13      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:51cto   func   print   log   ddr   cto   tps   fun   number   

http://blog.51cto.com/speakingbaicai/1703229
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, addr of x:%p\n", x, &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

golang闭包

标签:51cto   func   print   log   ddr   cto   tps   fun   number   

原文地址:https://www.cnblogs.com/liujitao79/p/9639650.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!