Go 支援 可匿名的函式,它們可以形成 封閉。當您想要在不命名的情況下,直接定義函式時,可匿名的函式便會非常有用。
|
|
|

package main
|
|
import "fmt"
|
函式 intSeq 會回傳另一個函式,我們在 intSeq 主體中以匿名的方式定義這個函式。這個回傳的函式會將變數 i 「封閉起來」,進而形成封閉。
|
func intSeq() func() int {
i := 0
return func() int {
i++
return i
}
}
|
|
func main() {
|
我們呼叫 intSeq ,將結果 (一個函式) 指定給 nextInt 。這個函式值會擷取它自己的 i 值,而這個值會在每次呼叫 nextInt 時更新。
|
nextInt := intSeq()
|
呼叫 nextInt 幾次,看看封閉的效果。
|
fmt.Println(nextInt())
fmt.Println(nextInt())
fmt.Println(nextInt())
|
為了確認狀態是那個特定函式獨有的,請建立並測試一個新的函式。
|
newInts := intSeq()
fmt.Println(newInts())
}
|