Callback function in GO language

0. Preface

Callback functions are a common technique in programming, often used in asynchronous programming. In simple terms, a callback function is a function that is passed to another function , and it is called at some point in that function to complete some specific operation or task .

In the Go language, a function can be directly passed as a parameter to another function and called when needed, which greatly enhances the customization of the code, but also reduces the readability of the code to a certain extent, so in Learn to choose when you actually use it.

1. use

  • Asynchronous programming: Usually, the callback function is called after the asynchronous operation is completed, so as to notify the caller that the operation has completed or return the result of the asynchronous operation. The callback function can be customized, so it can do some different work.
  • If there are several implementation methods for a certain logic, then the callback function can be used to decouple the implementation from the logic to improve reusability and maintainability. Examples include Simple Calculator and the sort.Slice function (code demo below).

2. A few examples

2.1 Access URL asynchronously

First define type callback func(data []byte, err error)the type as the callback function, then write the logic to read the URL (fetch function), in the main function, pass in the callback function and URL, and call this function asynchronously through the channel, by waiting for the return of the coroutine, where the WaitGroupcallback The function defines how the read content is used and is customizable.

package main

import (
   "fmt"
   "io/ioutil"
   "net/http"
   "sync"
   "time"
)

type callback func(data []byte, err error)
var wg sync.WaitGroup
func fetch(url string, c callback) {
   go func() {
      // 发送HTTP GET请求
      resp, err := http.Get(url)
      if err != nil {
         c(nil, err)
         return
      }
      defer resp.Body.Close()

      // 读取响应数据
      data, err := ioutil.ReadAll(resp.Body)
      if err != nil {
         c(nil, err)
         return
      }
      time.Sleep(10*time.Second)
      // 调用回调函数,传递响应数据和错误信息
      c(data, nil)
      wg.Done()
   }()
}

func main() {
   url := "https://www.baidu.com"
   wg.Add(1)
   fetch(url, func(data []byte, err error) {
      if err != nil {
         fmt.Println("Error:", err)
         return
      }
      fmt.Println(string(data))
   })
   fmt.Println("Waiting for response...")
   wg.Wait()
}

2.1 Sort.Slice function

The Sort.Slice function of the GO language uses the idea of ​​a callback function, and the logic of comparing the size is handed over to the user to implement, which greatly enhances the customization of the code. The following is an example of using it to size the string by the initial letter Sort:

package main

import (
   "fmt"
   "sort"
)

func main() {
   strs := []string{"apple", "orange", "banana", "pear"}
   sort.Slice(strs, func(i, j int) bool {
      return strs[i] < strs[j]
   })
   fmt.Println(strs)
}

2.2 Simple Calculator

In this example, a type Operation func(int, int) inttype as a callback function is defined, and then different implementations of this function are made. In the main function, the function name can be directly passed in to complete different logical operations.

package main

import "fmt"

type Operation func(int, int) int

func main() {
    // 加法运算
    result := calculate(10, 5, add)
    fmt.Println(result) // Output: 15

    // 减法运算
    result = calculate(10, 5, subtract)
    fmt.Println(result) // Output: 5

    // 乘法运算
    result = calculate(10, 5, multiply)
    fmt.Println(result) // Output: 50

    // 除法运算
    result = calculate(10, 5, divide)
    fmt.Println(result) // Output: 2
}

// 计算函数,接受两个整数和一个运算函数作为参数,返回运算结果
func calculate(a, b int, op Operation) int {
    return op(a, b)
}

// 加法函数,接受两个整数并返回它们的和
func add(a, b int) int {
    return a + b
}

// 减法函数,接受两个整数并返回它们的差
func subtract(a, b int) int {
    return a - b
}

// 乘法函数,接受两个整数并返回它们的积
func multiply(a, b int) int {
    return a * b
}

// 除法函数,接受两个整数并返回它们的商
func divide(a, b int) int {
    return a / b
}

Guess you like

Origin blog.csdn.net/doreen211/article/details/129334740