Go語言支持匿名函數(shù),可以形成閉包。匿名函數(shù)在想要定義函數(shù)而不必命名時(shí)非常有用。
所有的示例代碼,都放在
F:\worksp\golang目錄下。安裝Go編程環(huán)境請(qǐng)參考:http://www.yiibai.com/go/go_environment.html
函數(shù)intSeq()返回另一個(gè)函數(shù),它在intSeq()函數(shù)的主體中匿名定義。返回的函數(shù)閉合變量i以形成閉包。
當(dāng)調(diào)用intSeq()函數(shù),將結(jié)果(一個(gè)函數(shù))分配給nextInt。這個(gè)函數(shù)捕獲它自己的i值,每當(dāng)調(diào)用nextInt時(shí),它的i值將被更新。
通過調(diào)用nextInt幾次來查看閉包的效果。
要確認(rèn)狀態(tài)對(duì)于該特定函數(shù)是唯一的,請(qǐng)創(chuàng)建并測(cè)試一個(gè)新函數(shù)。
接下來我們來看看函數(shù)的最后一個(gè)特性是:遞歸。
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())
}
執(zhí)行上面代碼,將得到以下輸出結(jié)果 -
F:\worksp\golang>go run closures.go
1
2
3
1