go-回调函数

31次阅读

共计 515 个字符,预计需要花费 2 分钟才能阅读完成。

package main

import "fmt"

// go 回调函数
func main() {
    /*
        高阶函数:
               根据 go 语言函数的数据类型的特点,可以将函数作为另一个函数的参数
               fun1()
               fun2()
        将 fun1 函数作为 fun2 函数的参数:
            fun2 函数:高阶函数
                 接受一个函数作为参数的参数,叫做高阶函数
            fun1 函数:回调函数
                 作为另一个函数的参数的函数,叫回调函数
    */

    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
}

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

// 类型: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)
}

正文完
 0