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

















