# Go 閉包函數
Go支持匿名函數,匿名函數可以形成閉包。閉包函數可以訪問定義閉包的函數定義的內部變量。
示例1:
```go
package main
import "fmt"
// 這個"intSeq"函數返回另外一個在intSeq內部定義的匿名函數,
// 這個返回的匿名函數包住了變量i,從而形成了一個閉包
func intSeq() func() int {
i := 0
return func() int {
i += 1
return i
}
}
func main() {
// 我們調用intSeq函數,并且把結果賦值給一個函數nextInt,
// 這個nextInt函數擁有自己的i變量,這個變量每次調用都被更新。
// 這里i的初始值是由intSeq調用的時候決定的。
nextInt := intSeq()
// 調用幾次nextInt,看看閉包的效果
fmt.Println(nextInt())
fmt.Println(nextInt())
fmt.Println(nextInt())
// 為了確認閉包的狀態是獨立于intSeq函數的,再創建一個。
newInts := intSeq()
fmt.Println(newInts())
}
```
輸出結果為
```
1
2
3
1
```
示例2:
```go
package main
import "fmt"
func main() {
add10 := closure(10)//其實是構造了一個加10函數
fmt.Println(add10(5))
fmt.Println(add10(6))
add20 := closure(20)
fmt.Println(add20(5))
}
func closure(x int) func(y int) int {
return func(y int) int {
return x + y
}
}
```
輸出結果為:
```
15
16
25
```
示例3:
```go
package main
import "fmt"
func main() {
var fs []func() int
for i := 0; i < 3; i++ {
fs = append(fs, func() int {
return i
})
}
for _, f := range fs {
fmt.Printf("%p = %v\n", f, f())
}
}
```
輸出結果:
```
0x401200 = 3
0x401200 = 3
0x401200 = 3
```
示例4:
```go
package main
import "fmt"
func adder() func(int) int {
sum := 0
return func(x int) int {
sum += x
return sum
}
}
func main() {
result := adder()
for i := 0; i < 10; i++ {
fmt.Println(result(i))
}
}
```
輸出結果為:
```
0
1
3
6
10
15
21
28
36
45
```
- 版權
- 內容
- Go常量
- Go變量
- Go 數值
- Go 數組
- Go 字典
- Go 函數定義
- Go 方法
- Go 結構體
- Go 閉包函數
- Go 接口
- Go 字符串操作函數
- Go 字符串格式化
- Go 自定義排序
- Go Base64編碼
- Go Defer
- Go Exit.md
- Go for循環
- Go if..else if..else 條件判斷
- Go JSON支持
- Go Line Filters
- Go 狀態協程
- Go Panic
- Go range函數
- Go SHA1 散列
- Go String與Byte切片之間的轉換
- Go Switch語句
- Go URL解析
- Go 遍歷通道
- Go 并行功能
- Go 并行通道Channel
- Go 超時
- Go 錯誤處理
- Go 打點器
- Go 遞歸函數
- Go 讀取文件
- Go 工作池
- Go 關閉通道
- Go 函數多返回值
- Go 函數回調
- Go 函數命名返回值
- Go 互斥
- Go 環境變量
- Go 集合功能
- Go 計時器
- Go 進程觸發
- Go 進程執行
- Go hello world
- Go 可變長參數列表
- Go 命令行參數
- Go 命令行參數標記
- Go 排序
- Go 切片
- Go 請求處理頻率控制
- Go 時間
- Go 時間戳
- Go 時間格式化和解析
- Go 數字解析
- Go 隨機數
- Go 通道的同步功能
- Go 通道方向
- Go 通道緩沖
- Go 通道選擇Select
- Go 寫入文件
- Go 信號處理
- Go 原子計數器
- Go 正則表達式
- Go 指針