go实例之函数
1、可变参数
示例代码如下:
1 package main 2 3 import "fmt" 4 5 // Here's a function that will take an arbitrary number 6 // of `ints` as arguments. 7 func sum(nums ...int) { 8 fmt.Print(nums, " ") 9 total := 0 10 for _, num := range nums { 11 total += num 12 } 13 fmt.Println(total) 14 } 15 16 func main() { 17 18 // Variadic functions can be called in the usual way 19 // with individual arguments. 20 sum(1, 2) 21 sum(1, 2, 3) 22 23 // If you already have multiple args in a slice, 24 // apply them to a variadic function using 25 // `func(slice...)` like this. 26 nums := []int{1, 2, 3, 4} 27 sum(nums...) 28 }
执行上面代码,将得到以下输出结果
1 [1 2] 3 2 [1 2 3] 6 3 [1 2 3 4] 10
2、匿名函数
示例代码如下:
1 package main 2 3 import "fmt" 4 5 // This function `intSeq` returns another function, which 6 // we define anonymously in the body of `intSeq`. The 7 // returned function _closes over_ the variable `i` to 8 // form a closure. 9 func intSeq() func() int { 10 i := 0 11 return func() int { 12 i += 1 13 return i 14 } 15 } 16 17 func main() { 18 19 // We call `intSeq`, assigning the result (a function) 20 // to `nextInt`. This function value captures its 21 // own `i` value, which will be updated each time 22 // we call `nextInt`. 23 nextInt := intSeq() 24 25 // See the effect of the closure by calling `nextInt` 26 // a few times. 27 fmt.Println(nextInt()) 28 fmt.Println(nextInt()) 29 fmt.Println(nextInt()) 30 31 // To confirm that the state is unique to that 32 // particular function, create and test a new one. 33 newInts := intSeq() 34 fmt.Println(newInts()) 35 }
执行上面代码,将得到以下输出结果
1 1 2 2 3 3 4 1
3、递归函数
示例代码如下:
1 package main 2 3 import "fmt" 4 5 // This `fact` function calls itself until it reaches the 6 // base case of `fact(0)`. 7 func fact(n int) int { 8 if n == 0 { 9 return 1 10 } 11 return n * fact(n-1) 12 } 13 14 func main() { 15 fmt.Println(fact(7)) 16 }
这个fact()
函数实际上是调用它自己本身,直到它达到fact(0)
时结果退出。
相关链接: