Learning Functional Programming in Go
上QQ阅读APP看书,第一时间看更新

A quick example of a function literal

See that {ret = n + 2} is our anonymous function/function literal/closure/lambda expression.

Our function literal:

  • Is written like a function declaration, but without a function name following the func keyword
  • Is an expression
  • Has access to all the variables available in its lexical scope (n in our case)
package main

func curryAddTwo(n int) (ret int) {
defer func(){ret = n + 2}()
return n
}

func main() {
println(curryAddTwo(1))
}

The output is as follows:

3

Note that we used the defer statement to delay the execution of our function literal until after its surrounding function (curryAddTwo) is returned. Since our anonymous function has access to all the variables in its scope (n), it can modify n. The modified value is what gets printed.