go callback function

Posted Jun 7, 20201 min read

package main

import "fmt"

//go callback function
func main() {
    /*
        Higher order functions:
               According to the characteristics of the data type of the go language function, the function can be used as the parameter of another function
               fun1()
               fun2()
        Use the fun1 function as the parameter of the fun2 function:
            fun2 function:higher order function
                 Accepts a function as a parameter, called a higher-order function
            fun1 function:callback function
                 A function that is a parameter of another function is called a callback function
    */

    fmt.Printf("%T\n", add) //func(int, int) int
    fmt.Printf("%T\n", oper) //func(int, int, func(int, int) int) int

    res1 := add(1, 2)
    fmt.Println(res1) //3

    res2 := oper(1, 2, add)
    fmt.Println(res2) //3
}

//Type:func(int,int)int
func add(a, b int) int {
    return a + b
}

//Type:func(int,int, func(int,int)int)int
func oper(m, n int, fun func(int, int) int) int {
    //res := fun(1, 2)
    //return res
    return fun(1, 2)
}