英文:
Pass a function body/defintion as parameter to a function call in golang
问题
最近在使用golang时,我遇到了以下问题。是否可以像JavaScript一样将函数体传递给函数调用?
在JavaScript中,将匿名函数传递给另一个函数是非常常见的。我想知道在Go语言中是否也是如此?
package main
import (
"fmt"
)
type HandlerFunc func(int)
func main() {
// 将函数定义为对象/变量?
hnd := func(in int){
fmt.Println("func handler returns input", in)
}
a := HandlerFunc(hnd) // 将函数对象/变量传递给类型HandlerFunc
a(10)
// 直接将函数体传递给类型HandlerFunc
b := HandlerFunc(func(_in int){
fmt.Println("another func handler returns input", _in)
})
b(100)
fmt.Println("Hello, playground")
}
这两种方法都可以工作,但我想知道这两种用法之间是否有任何区别?哪一种更可取?
英文:
I am come across the following question recently in using golang. Is it ok to pass a function body to a function call, like javascript.
e.g. setTimeout(function(i){console.log("input:", i)}, 1000).
It's pretty common to pass an anonymous function to another function in javascript. I was wondering if is the same in 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")
}
They both works, but I was wondering if there is any difference between these two use, And which one is more preferable?
答案1
得分: 1
没有区别,使用适合你风格的那个。
英文:
There is no difference, use the one that better fits your style.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论