golang 函数作为参数传递(回调)

和其他很多语言一样,golang中函数也可以作为其它函数的参数进行传递,然后在其它函数内调用执行,一般称之为回调。

语法:以函数签名作为主调函数的形参的类型,即传递一个指向函数的指针

func main() {
sayhello("john", addperfix)
}

func addperfix(perfix, name string) {
fmt.Println(perfix, "!", name)
}

func sayhello(name string, f func(string, string)) {
f("hello", name)
}

猜你喜欢

转载自www.cnblogs.com/ExMan/p/12622205.html