初学Golang:闭包作为参数与返回值的使用

Code Speaks:

 

 1 package main
 2 
 3 import "fmt"
 4 
 5 /**
 6  * 定义处理器函数
 7  */
 8 func handle(callback func() func() int) int{
 9       /**
10       * 生成闭包中的处理器
11      * @type {[type]}
12       */
13       dealer := callback()
14 
15       /**
16       * 调用闭包中的处理器
17      */
18       return dealer()
19 }
20 /**
21  * main 函数入口
22  * @return {[type]} [description]
23  */
24 func main() {
25        /**
26        * 调用处理器并定义回调
27       * @type {[type]}
28        */
29        res := handle(func() func() int{
30               num := 1
31 
32               /**
33                * 返回闭包函数
34             */
35              return func() int{
36                      num += 1
37                      return num
38               }
39         })
40 
41         fmt.Println(res)
42 }

 

 

输出  2

posted @ 2016-10-26 01:50  小天儿  阅读(1109)  评论(0)    收藏  举报