funcfibonacci(n int)int { if n <= 2 { return1 } return fibonacci(n-1) + fibonacci(n-2) }
funcmain() { for i := 0; i <= 10; i++ { fmt.Printf("fibonacci(%d) is: %d\n", i, fibonacci(i)) } }
上述代码运行结果为:
1 2 3 4 5 6 7 8 9 10
fibonacci(1) is: 1 fibonacci(2) is: 1 fibonacci(3) is: 2 fibonacci(4) is: 3 fibonacci(5) is: 5 fibonacci(6) is: 8 fibonacci(7) is: 13 fibonacci(8) is: 21 fibonacci(9) is: 34 fibonacci(10) is: 55
闭包
闭包其实就是匿名函数。匿名函数,顾名思义就是没有名称的函数,通常定义格式为:
1 2 3
func(参数列表)(返回参数列表){ 函数体 }
我们来看一个例子,如何构建一个匿名函数并调用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
package main
import"fmt"
funcmain() { f() }
funcf() { g := func(i int) { // 创建一个匿名函数,并赋值给变量 g fmt.Printf("%d ", i) }
for i := 0; i < 4; i++ { g(i) // 调用匿名函数 fmt.Printf(" - g is of type %T and has value %v\n", g, g) } }
上述代码运行结果为:
1 2 3 4
0 - g is of type func(int) and has value 0x1056b20 1 - g is of type func(int) and has value 0x1056b20 2 - g is of type func(int) and has value 0x1056b20 3 - g is of type func(int) and has value 0x1056b20
通过以上示例我们可以了解到 g 的类型是 func(int),它的值是内存地址。
现在有两个函数 Add2() 和 Adder(),它们都返回类型为 func(b int) int 的函数:
funcmain() { // make an Add2 function, give it a name p2, and call it: p2 := Add2() fmt.Printf("Call Add2 for 3 gives: %v\n", p2(3)) // make a special Adder function, a gets value 3: TwoAdder := Adder(2) fmt.Printf("The result is: %v\n", TwoAdder(3)) }