问题描述
我来自具有一流功能支持的JavaScript。例如,您可以:- 将函数作为参数传递给另一个函数
- 返回一个函数从一个函数。
有人可以给我一个例子,说明我如何在Go中执行此操作?
可能会有所帮助。在这篇博文中:
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $'
func foo()string {
returnStringy function
}
func takesAFunction(foo Stringy){
fmt.Printf(takesAFunction:%v \ ()返回func()字符串{
fmt.Printf(内部函数函数\ n);函数返回函数的返回值。
returnbar//必须返回一个字符串以获得stringy
}
}
func main(){
takesAFunction(foo);
var f Stringy = returnsAFunction();
f();
var baz Stringy = func()string {
returnanonymous stringy\\\
};
fmt.Printf(baz());
}
作者是博主:Dethe Elza(不是我)
I come from JavaScript which has first class function support. For example you can:
- pass a function as a parameter to another function
- return a function from a function.
Can someone give me an example of how I would do this in Go?
Go Language and Functional Programming might help. From this blog post:
package main
import fmt "fmt"
type Stringy func() string
func foo() string{
return "Stringy function"
}
func takesAFunction(foo Stringy){
fmt.Printf("takesAFunction: %v\n", foo())
}
func returnsAFunction()Stringy{
return func()string{
fmt.Printf("Inner stringy function\n");
return "bar" // have to return a string to be stringy
}
}
func main(){
takesAFunction(foo);
var f Stringy = returnsAFunction();
f();
var baz Stringy = func()string{
return "anonymous stringy\n"
};
fmt.Printf(baz());
}
Author is the blog owner: Dethe Elza (not me)
这篇关于Go的头等功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!