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)时结果退出。

相关链接:

  Go可变参数的函数实例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值