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
本文通过一个Go语言的示例介绍了如何使用闭包和回调函数。代码中定义了一个handle函数,它接受一个返回func()int类型的回调函数作为参数,并在内部执行该回调函数。main函数中演示了如何调用handle函数。
2048

被折叠的 条评论
为什么被折叠?



