5.6 Anonymous Functions
Named functions can be declared only at the package level, but we can
use a function literal to denote a function value within any
expression.
A function literal is written like a function declaration, but without
a name following the func
keyword.
It is an expression, and its value is called an
anonymous function.
Function literals let us define a function at its point of use.
As an example, the
earlier call to strings.Map
can be rewritten as
strings.Map(func(r rune) rune { return r + 1 }, "HAL-9000")
More importantly, functions defined in this way have access to the entire lexical environment, so the inner function can refer to variables from the enclosing function, as this example ...
Get The Go Programming Language now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.