This is a creation in Article, where the information may have evolved or changed.
1. Definition
A callback function is a function that is called through a function pointer. If you pass the pointer (address) of the function as an argument to another function, when the pointer is used to invoke the function it points to, we say this is a callback function. The callback function is not called directly by the implementing party of the function, but is invoked by another party when a particular event or condition occurs, and is used to respond to the event or condition.
2. Mechanism
- Define a callback function
- A party that provides a function implementation registers the function pointer of the callback function with the caller at initialization time
- When a specific event or condition occurs, the caller uses a function pointer to invoke the callback function to process the event
Example 1. This is a simple callback example, calling the function test when calling the real implementation function add
package mainimport "fmt"type Callback func(x, y int) int// 提供一个接口,让外部去实现func test(x, y int, callback Callback) int { return callback(x, y)}// 回调函数的具体实现func add(x, y int) int { return x + y}func main() { x, y := 1, 2 fmt.Println(test(x, y, add))}
Example 2. This is an example of converting a string to an int, executing a callback function in the event of a conversion failure, and outputting an error message
package mainimport ( "strconv" "fmt")type Callback func(msg string)//将字符串转换为int64,如果转换失败调用Callbackfunc stringToInt(s string, callback Callback) int64 { if value, err := strconv.ParseInt(s, 0, 0); err != nil { callback(err.Error()) return 0 } else { return value }}// 记录日志消息的具体实现func errLog(msg string) { fmt.Println("Convert error: ", msg)}func main() { fmt.Println(stringToInt("18", errLog)) fmt.Println(stringToInt("hh", errLog))}
Through the two simple examples above, believe that you already know Golang's callback wit