GO 函数 回调(阻塞式)

2018-05-11  本文已影响0人  samsing

理解什么是回调请参考:https://www.zhihu.com/question/19801131/answer/27459821
再实现函数回调之前需要先阐述一下一个知识点 function type,官方的解释如下:

A function type denotes the set of all functions with the same parameter and result types. The value of an uninitialized variable of function type is nil.

Go支持函数回调,你可以把函数名称作为参数传递给另外一个函数,然后在别的地方实现这个函数。

package main
import "fmt"
type Callback func(x, y int) int

func main() {
    x, y := 1, 2
        result = double_add(x, y, add)
    fmt.Println(result)
}

//提供一个接口,让外部去实现
func double_add(x, y int, callback Callback) int {
    return callback(x, y) * 2
}

func add(x, y int) int {
    return x + y
}

运行结果

6
上一篇 下一篇

猜你喜欢

热点阅读