Does Go have lambda expressions or anything similar?

Viewed 92507

Does Go support lambda expressions or anything similar?

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

7 Answers

The golang does not seem to make lambda expressions, but you can use a literal anonymous function, I wrote some examples when I was studying comparing the equivalent in JS, I hope it helps !!

no args return string:

func() string {
    return "some String Value"
}
//Js similar: () => 'some String Value'

with string args and return string

func(arg string) string {
    return "some String" + arg
}
//Js similar: (arg) => "some String Value" + arg

no arguments and no returns (void)

func() {
   fmt.Println("Some String Value")
} 
//Js similar: () => {console.log("Some String Value")}

with Arguments and no returns (void)

func(arg string) {
    fmt.Println("Some String " + arg)
}
//Js: (arg) => {console.log("Some String Value" + arg)}

An example that hasn't been provided yet that I was looking for is to assign values directly to variable/s from an anonymous function e.g.

test1, test2 := func() (string, string) {
    x := []string{"hello", "world"}
    return x[0], x[1]
}()

Note: you require brackets () at the end of the function to execute it and return the values otherwise only the function is returned and produces an assignment mismatch: 2 variable but 1 values error.

Here is a 'curried function' example. However the syntax seems unclear, relative to the lambda function syntax in other languages such as Swift, C#, etc.

func main() int { 
  var f func(string) func(string) int
  f = func(_x1 string) func(string) int { return func(_x2 string) int { return strings.Compare(_x1,_x2) } }
  return ((f)("b"))("a")
}

Yes, since it is a fully functional language, but has no fat arrow (=>) or thin arrow (->) as the usual lambda sign, and uses the func keyword for the sake of clarity and simplicity.

Related