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).


这里是一个例子,仔细复制和粘贴:

package main

import fmt "fmt"

type Stringy func() string

func foo() string{
  return "Stringy function"
}

func takesAFunction(foo Stringy){
  fmt.Printf("takesAFunction: %vn", foo())
}

func returnsAFunction()Stringy{
  return func()string{
    fmt.Printf("Inner stringy functionn");
    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 stringyn"
  };
  fmt.Printf(baz());
}

Lambda expressions are also called function literals. Go supports them completely.

See the language spec: http://golang.org/ref/spec#Function_literals

See a code-walk, with examples and a description: http://golang.org/doc/codewalk/functions/


Yes

In computer programming, an anonymous function or lambda abstraction (function literal) is a function definition that is not bound to an identifier, and Go supports anonymous functions , which can form closures. Anonymous functions are useful when you want to define a function inline without having to name it.

    package main
    import "fmt"

    func intSeq() func() int {
        i := 0
        return func() int {
            i += 1
            return i
        }
    }


    func main() {
       nextInt := intSeq()
       fmt.Println(nextInt())
       fmt.Println(nextInt())
       fmt.Println(nextInt())
       newInts := intSeq()
       fmt.Println(newInts())
    }

function intSeq returns another function, which we define anonymously in the body of intSeq. The returned function closes over the variable i to form a closure .

Output
$ go run closures.go
1
2
3
1
链接地址: http://www.djcxy.com/p/51282.html

上一篇: Java 8是否支持闭包?

下一篇: Go有lambda表达式或类似的东西吗?