# Go知识盲区--闭包

## 2. 什么是闭包？

### 2.1. 一个简单的例子

package main

import (
"fmt"
)

// 累加器
var n int = 10
return func(x int) int {
n = n + x
return n
}
}

func main() {

fmt.Println(f(1)) // 11
fmt.Println(f(2)) // 13
fmt.Println(f(3)) // 16
}


### 2.2理解闭包

1. 闭包本身是一个函数, 且返回的一个函数func (int) int
2. 返回的是一个匿名函数,但是这个匿名函数 引用到了函数(匿名)函数外的变量(上面示例是 n),因此这个匿名函数就和n 形成了一个整体, 构成闭包.
3. 相比较类可以这么理解: 闭包是类(class),函数是类里面的某个方法, n是字段(属性),函数和他使用到的n构成闭包

## 3. 复杂的闭包场景

import "fmt"

func func1() (i int) {
i = 10
defer func() {
i += 1
}()
// 相当于两条语句
// i = 5
// return i
return 5
}

func main() {
closure := func1()
fmt.Println(closure)
}


## 4.闭包的底层原理？

package main

import (
"fmt"
)

// 累加器
var n int = 10
return func(x int) int {
n = n + x
return n
}
}

func main() {

fmt.Println(f(1)) // 11
fmt.Println(f(2)) // 13
fmt.Println(f(3)) // 16
}


D:\gopath\src\Go_base\daily_test\闭包> go build -gcflags="-m -m -l" demo.go
# command-line-arguments
.\demo.go:10:9: func literal escapes to heap:
.\demo.go:10:9:   flow: ~r0 = &{storage for func literal}:
.\demo.go:10:9:     from func literal (spill) at .\demo.go:10:9
.\demo.go:10:9:     from return func literal (return) at .\demo.go:10:2
.\demo.go:9:6: n escapes to heap:
.\demo.go:9:6:   flow: {storage for func literal} = &n:
.\demo.go:9:6:     from func literal (captured by a closure) at .\demo.go:10:9
.\demo.go:9:6:     from n (reference) at .\demo.go:11:7
.\demo.go:9:6: moved to heap: n
.\demo.go:10:9: func literal escapes to heap
.\demo.go:21:15: f(3) escapes to heap:
.\demo.go:21:15:   flow: {storage for ... argument} = &{storage for f(3)}:
.\demo.go:21:15:     from f(3) (spill) at .\demo.go:21:15
.\demo.go:21:15:     from ... argument (slice-literal-element) at .\demo.go:21:13
.\demo.go:21:15:   flow: {heap} = {storage for ... argument}:
.\demo.go:21:15:     from ... argument (spill) at .\demo.go:21:13
.\demo.go:21:15:     from fmt.Println(... argument...) (call parameter) at .\demo.go:21:13
.\demo.go:20:15: f(2) escapes to heap:
.\demo.go:20:15:   flow: {storage for ... argument} = &{storage for f(2)}:
.\demo.go:20:15:     from f(2) (spill) at .\demo.go:20:15
.\demo.go:20:15:     from ... argument (slice-literal-element) at .\demo.go:20:13
.\demo.go:20:15:   flow: {heap} = {storage for ... argument}:
.\demo.go:20:15:     from ... argument (spill) at .\demo.go:20:13
.\demo.go:20:15:     from fmt.Println(... argument...) (call parameter) at .\demo.go:20:13
.\demo.go:19:15: f(1) escapes to heap:
.\demo.go:19:15:   flow: {storage for ... argument} = &{storage for f(1)}:
.\demo.go:19:15:     from f(1) (spill) at .\demo.go:19:15
.\demo.go:19:15:     from ... argument (slice-literal-element) at .\demo.go:19:13
.\demo.go:19:15:   flow: {heap} = {storage for ... argument}:
.\demo.go:19:15:     from ... argument (spill) at .\demo.go:19:13
.\demo.go:19:15:     from fmt.Println(... argument...) (call parameter) at .\demo.go:19:13
.\demo.go:19:13: ... argument does not escape
.\demo.go:19:15: f(1) escapes to heap
.\demo.go:20:13: ... argument does not escape
.\demo.go:20:15: f(2) escapes to heap
.\demo.go:21:13: ... argument does not escape
.\demo.go:21:15: f(3) escapes to heap


D:\gopath\src\Go_base\daily_test\闭包>go build -gcflags="-S" demo.go
# command-line-arguments
"".AddWrapper STEXT size=159 args=0x8 locals=0x20 funcid=0x0
0x0000 00000 (D:\gopath\src\Go_base\daily_test\闭包\demo.go:8)  TEXT    "".AddWrapper(SB), ABIInternal, $32-8 0x0000 00000 (D:\gopath\src\Go_base\daily_test\闭包\demo.go:8) MOVQ TLS, CX 0x0009 00009 (D:\gopath\src\Go_base\daily_test\闭包\demo.go:8) PCDATA$0, \$-2
0x0045 00069 (D:\gopath\src\Go_base\daily_test\闭包\demo.go:10) LEAQ    type.noalg.struct { F uintptr; "".n *int }(SB), CX



type.noalg.struct { F uintptr; "".n *int }


## 5. 迷题揭晓

import "fmt"

func func1() (i int) {
i = 10
defer func() {
i += 1
}()
return 5
}

func main() {
closure := func1()
fmt.Println(closure)
}

1. 首先，由于 i在函数定义的返回值上声明，因此根据 go 的 caller-save 模式， i 变量会存储在 main 函数的栈空间。

1. Callee-saved register（又称非易失性寄存器AKA non-volatile registers, or call-preserved）用于保存应在每次调用中保留的长寿命值。
2. 调用者保存”（ caller saving ）方法：如果采用调用者保存策略，那么在一个调用者调用别的过程时，必须保存调用者所要保存的寄存器，以备调用结束返回后，能够再次访问调用者。
2. 然后，func1 的 return 重新把 5 赋值给了 i ，此时 i = 5

3. 由于闭包函数存储了这个变量 i 的指针。

4. 因此最后，在 defer 中对 i 进行自增，是直接更新到 i 的指针上，此时 i = 5+1，所以最终打印出来的结果是 6

## 6. 可能的坑

func1 的返回值我们不写变量名 i 了，然后原先返回具体字面量，现在改成变量 i ，就是这两小小小的改动，会导致运行结果大大不同。

import "fmt"

func func1() (int) {
i := 10

defer func() {
// 函数内部的作用域并不会作用到外部
i += 1
}()
return i
}

func main() {
closure := func1()
fmt.Println(closure)
}


## 8. 参考

posted @ 2021-12-08 00:25  failymao  阅读(462)  评论(2编辑  收藏  举报