最近在使用golang的过程中遇到了如下问题。将函数体传递给函数调用是否可以,例如 javascript。
例如setTimeout(function(i){console.log("input:", i)}, 1000).
在 javascript 中将匿名函数传递给另一个函数是很常见的。我想知道在 go 中是否相同?
package main
import (
"fmt"
)
type HandlerFunc func(int)
func main() {
// define a function as object/variable?
hnd := func(in int){
fmt.Println("func handler returns input", in);
}
a:=HandlerFunc(hnd) //pass function object/variable to type HandlerFunc
a(10)
// pass function body directly to type HandlerFunc
b:=HandlerFunc(func(_in int){
fmt.Println("another func handler returns input", _in);
})
b(100)
fmt.Println("Hello, playground")
}
它们都有效,但我想知道这两种用法之间是否有任何区别,哪种更可取?
最佳答案
没有区别,使用更适合您风格的那个。
关于function - 将函数体/定义作为参数传递给 golang 中的函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42646717/