First class functions in Go

前端 未结 5 1505
鱼传尺愫
鱼传尺愫 2021-01-30 08:49

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 f
5条回答
  •  日久生厌
    2021-01-30 09:12

    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)

提交回复
热议问题