liveBook · Manning

Lambda

As explained in Learn Go with Pocket-Sized Projects

An anonymous function is a function value declared without a name, typically for inline or temporary use.

A lambda is an anonymous function: a function value declared without a name for inline, temporary, or task-specific logic. In Go, it can be passed as an argument or executed immediately. section 3.2.3

Sort books with a lambda

Pass a comparison function directly to sort.Slice. The example orders books by author, then title, keeping the sorting rule beside the call that uses it. section 3.2.3

Listing 3.18 bookworm.go: Sorting the books
// sortBooks sorts the books by Author and then Title.
func sortBooks(books []Book) []Book {
    sort.Slice(books, func(i, j int) bool { #1
        if books[i].Author != books[j].Author {
            return books[i].Author < books[j].Author #2
        }
        return books[i].Title < books[j].Title #2
    })

    return books
}

The lambda compares two slice indices and returns whether the first book should precede the second. section 3.2.3

Lambdas also support concurrent work:

  • Wrap goroutine work and cleanup together by calling explore and defer wg.Done inside one anonymous function. section 9.5.1
  • Pass the loop value as a parameter to avoid older Go loop-variable capture behavior when starting concurrent activities. section 9.5.1
Listing 9.25 explore.go: Stop listening to new messages
func (s *Solver) listenToBranches() {
    wg := sync.WaitGroup{}
    defer wg.Wait() #1

    for p := range s.pathsToExplore {
        wg.Add(1) #2
        go func(path *path) {
            defer wg.Done() #3
            s.explore(path)
        }(p) #4
        if s.solution != nil {
            return
        }
    }
}

The listing combines a WaitGroup, deferred cleanup, a parameterized lambda, and a goroutine. section 9.5.1

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Defines lambdas, demonstrates sorting, and explains loop-variable capture, but does not develop closure internals broadly.
Examples
Demonstrates book sorting and concurrent maze exploration with a parameterized goroutine function.
What you can do after
Apply it via sort.Slice and goroutines while avoiding older Go loop-variable capture problems.
How it connects
Connects lambdas to function arguments, sort.Slice, closures, goroutines, channels, and sync.WaitGroup.

Also explained in

Compare how 18 books explain lambda →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.