concept anonymous function in category go

appears as: nonymous functions, An onymous function, n anonymous function, Anonymous functions, The onymous function, onymous function
Get Programming with Go

This is an excerpt from Manning's book Get Programming with Go.

14.4. Closures and anonymous functions

An anonymous function, also called a function literal in Go, is a function without a name. Unlike regular functions, function literals are closures because they keep references to variables in the surrounding scope.

You can assign an anonymous function to a variable and then use that variable like any other function, as shown in the following listing.

You can even declare and invoke an anonymous function in one step, as shown in the following listing.

Listing 14.5. Anonymous function: anonymous.go
package main

import "fmt"

func main() {
    func() {                                #1
        fmt.Println("Functions anonymous")
    }()                                     #2
}

Anonymous functions can come in handy whenever you need to create a function on the fly. One such circumstance is when returning a function from another function. Although it’s possible for a function to return an existing named function, declaring and returning a new anonymous function is much more useful.