理解什么是回調請參考: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