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

相关文章

什么是Go的接口? 接口可以说是一种类型,可以粗略的理解为他...
1、Golang指针 在介绍Golang指针隐式间接引用前,先简单说下...
1、概述 1.1 Protocol buffers定义 Protocol buffe...
判断文件是否存在,需要用到"os"包中的两个函数: os.Stat(...
1、编译环境 OS :Loongnix-Server Linux release 8.3 CPU指...
1、概述 Golang是一种强类型语言,虽然在代码中经常看到i:=1...