golang闭包
Posted liujitao79
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang闭包相关的知识,希望对你有一定的参考价值。
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
", x, &x)
return func(y int) {
k := x + y
x = k
y = k
fmt.Printf("x: %d, addr of x:%p
", x, &x)
fmt.Printf("y: %d, addr of y:%p
", 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闭包的主要内容,如果未能解决你的问题,请参考以下文章