golambda

Does Go have lambda expressions or anything similar?


Does Go support lambda expressions or anything similar?

I want to port a library from another language that uses lambda expressions (Ruby).


Solution

  • Yes.

    Here is an example, copied and pasted carefully:

    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());
    }