将一个函数体/定义作为参数传递给golang中的函数调用。

huangapple go评论107阅读模式
英文:

Pass a function body/defintion as parameter to a function call in golang

问题

最近在使用golang时,我遇到了以下问题。是否可以像JavaScript一样将函数体传递给函数调用?

在JavaScript中,将匿名函数传递给另一个函数是非常常见的。我想知道在Go语言中是否也是如此?

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type HandlerFunc func(int)
  6. func main() {
  7. // 将函数定义为对象/变量?
  8. hnd := func(in int){
  9. fmt.Println("func handler returns input", in)
  10. }
  11. a := HandlerFunc(hnd) // 将函数对象/变量传递给类型HandlerFunc
  12. a(10)
  13. // 直接将函数体传递给类型HandlerFunc
  14. b := HandlerFunc(func(_in int){
  15. fmt.Println("another func handler returns input", _in)
  16. })
  17. b(100)
  18. fmt.Println("Hello, playground")
  19. }

这两种方法都可以工作,但我想知道这两种用法之间是否有任何区别?哪一种更可取?

英文:

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?

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type HandlerFunc func(int)
  6. func main() {
  7. // define a function as object/variable?
  8. hnd := func(in int){
  9. fmt.Println("func handler returns input", in);
  10. }
  11. a:=HandlerFunc(hnd) //pass function object/variable to type HandlerFunc
  12. a(10)
  13. // pass function body directly to type HandlerFunc
  14. b:=HandlerFunc(func(_in int){
  15. fmt.Println("another func handler returns input", _in);
  16. })
  17. b(100)
  18. fmt.Println("Hello, playground")
  19. }

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.

huangapple
  • 本文由 发表于 2017年3月7日 19:09:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/42646717.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定