Go的头等功能 [英] First class functions in Go

查看:89
本文介绍了Go的头等功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自具有一流功能支持的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的头等功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆