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

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

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.

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:

确定