> For the complete documentation index, see [llms.txt](https://books.innohub.top/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://books.innohub.top/goinfo/info/closure.md).

# 函数闭包

\[TOC]

## 1.  闭包的概念

Closure 又被称为词法闭包，函数闭包，是引用了自有变量的函数。该被引用的自由变量将和函数一同存在，即使离开了自由变量的创建环境。所以实现闭包的关键操作在于，自由变量不可以在栈上分配，必须在堆上进行内存分配。同时闭包需要返回一个函数，所以函数必须作为**第一类值**，函数可以作为普通变量使用。

```go
func fibo() func() int {
        res := []int{0, 0}
        return func() int {
                if res[1] == 0 {
                        res[1] = 1
                        return 0
                }
                res[0], res[1] = res[1], res[0] + res[1]
                return res[0]
        }
}
```
