闭包
Go 支持通过 闭包”) 来使用 匿名函数。匿名函数在你想定义一个不需要命名的内联函数时是很实用的。
代码实例
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`。这个函数的值包含了自己的值 `i`,这样在每 // 次调用 `nextInt` 是都会更新 `i` 的值。 nextInt := intSeq() // 通过多次调用 `nextInt` 来看看闭包的效果。 fmt.Println(nextInt()) fmt.Println(nextInt()) fmt.Println(nextInt()) // 为了确认这个状态对于这个特定的函数是唯一的,我们 // 重新创建并测试一下。 newInts := intSeq() fmt.Println(newInts()) }
将代码保存为 E:\FangCloudSync\Work\LSource\golang\chapter06\closures.go
运行程序
go run E:\FangCloudSync\Work\LSource\golang\chapter06\closures.go
输出:
Go
1 2 3 1
递归
Go 支持 递归。
这里是一个经典的阶乘示例。
代码实例
Go
package main import "fmt" // `face` 函数在到达 `face(0)` 前一直调用自身。 func fact (n int ) int { if n == 0 { return 1 } return n * fact(n -1 ) } func main () { fmt.Println(fact( 7 )) }
将代码保存为 E:\FangCloudSync\Work\LSource\golang\chapter06\recursion.go
运行代码
go run E:\FangCloudSync\Work\LSource\golang\chapter06\recursion.go
输出:
Go
5040
更多IT教程资源,尽在求课吧[51cesi.com]