Course › Week 3 · Real data and speed › Day 5 · lesson 19 of 42 · 20 min reading + 60 min practice
Closures and the slices package
Functions as values, what a closure captures, and sorting and searching with slices and maps.
On this page
In Go a function is a value like any other: it has a type, it can be stored in a variable, passed to another function and returned from one. A function written inside another can use that function’s variables, which makes it a closure.
Today: function values, closures, and the standard library packages that take functions as arguments: slices for sorting and searching, maps for keys. Then the generic method that the generics lesson promised.
Functions as values
1. A function type
func(int) int is the type of a function that takes an int and returns an int. Any function with that signature can be passed where it is expected.
package main
import "fmt"
func weekendRate(cents int) int {
return cents * 120 / 100
}
func lowSeason(cents int) int {
return cents * 80 / 100
}
func applyAll(cents []int, rule func(int) int) []int {
result := make([]int, 0, len(cents))
for _, c := range cents {
result = append(result, rule(c))
}
return result
}
func main() {
nightly := []int{12950, 9900}
fmt.Println(applyAll(nightly, weekendRate))
fmt.Println(applyAll(nightly, lowSeason))
}
[15540 11880]
[10360 7920]weekendRate without parentheses is the function itself, not a call. It is PHP’s first-class callable weekendRate(...), with the signature checked at compile time.
2. A function literal
A function without a name can be written right where it is needed. You met one in the t.Run of the tests lesson.
package main
import "fmt"
func applyAll(cents []int, rule func(int) int) []int {
result := make([]int, 0, len(cents))
for _, c := range cents {
result = append(result, rule(c))
}
return result
}
func main() {
nightly := []int{12950, 9900}
withFee := applyAll(nightly, func(cents int) int {
return cents + 1500
})
fmt.Println(withFee)
}
[14450 11400]It is PHP’s anonymous function, function (int $cents): int { … }, and like PHP’s arrow functions it can use the variables around it, as the next section shows.
3. A closure keeps its variables
A function literal can use variables of the function it is written in, and it keeps them for as long as it lives, even after that function has returned.
package main
import "fmt"
// newIDGenerator returns a function that gives the next booking ID each time it is called.
func newIDGenerator(start int) func() int {
next := start
return func() int {
id := next
next++
return id
}
}
func main() {
nextID := newIDGenerator(1042)
fmt.Println(nextID(), nextID(), nextID())
other := newIDGenerator(9000)
fmt.Println(other(), nextID())
}
1042 1043 1044
9000 1045Each call of newIDGenerator creates a new next, and the returned function holds on to it. The two generators do not share anything. PHP needs use (&$next) to get the same effect; in Go every variable a closure uses is shared with it, never copied.
4. Each loop round has its own variable
Closures made in a loop capture that round’s loop variable, so each one sees its own value:
package main
import "fmt"
func main() {
var printers []func()
for _, guest := range []string{"Astrid", "Bjorn", "Clara"} {
printers = append(printers, func() {
fmt.Println("welcome,", guest)
})
}
for _, p := range printers {
p()
}
}
welcome, Astrid
welcome, Bjorn
welcome, ClaraThis is true since Go 1.22. Before it, all three closures shared one guest and printed Clara three times, the most famous Go bug. You will still see old code that works around it with guest := guest inside the loop; that line is no longer needed.
The slices and maps packages
5. Sorting by a field
slices.SortFunc(s, compare) sorts a slice in place, using a function that compares two elements: negative when a comes first, positive when b does, 0 when they are equal. cmp.Compare returns exactly that for two ordered values.
package main
import (
"cmp"
"fmt"
"slices"
)
type Booking struct {
Guest string
Nights int
}
func main() {
bookings := []Booking{{"Clara", 2}, {"Astrid", 7}, {"Bjorn", 3}, {"Dagny", 7}}
slices.SortFunc(bookings, func(a, b Booking) int {
if c := cmp.Compare(b.Nights, a.Nights); c != 0 {
return c
}
return cmp.Compare(a.Guest, b.Guest)
})
for _, b := range bookings {
fmt.Println(b.Nights, b.Guest)
}
}
7 Astrid
7 Dagny
3 Bjorn
2 ClaraComparing b with a (not a with b) sorts the nights from the most. Astrid and Dagny tie on 7, so the second comparison sorts them by name. Always end with a tie-breaker that cannot tie: without one, equal elements may come out in any order.
It is PHP’s usort with the spaceship operator <=>; cmp.Compare is the spaceship.
6. Searching
The slices package has a function for most loops you would write by hand. The ones ending in Func take a function that tests or compares elements.
package main
import (
"cmp"
"fmt"
"slices"
)
type Booking struct {
Guest string
Nights int
}
func main() {
bookings := []Booking{{"Clara", 2}, {"Astrid", 7}, {"Bjorn", 3}}
i := slices.IndexFunc(bookings, func(b Booking) bool { return b.Guest == "Bjorn" })
fmt.Println("Bjorn is at", i)
longStay := slices.ContainsFunc(bookings, func(b Booking) bool { return b.Nights >= 7 })
fmt.Println("any long stay:", longStay)
longest := slices.MaxFunc(bookings, func(a, b Booking) int { return cmp.Compare(a.Nights, b.Nights) })
fmt.Println("longest:", longest.Guest)
fmt.Println(slices.Contains([]string{"INFO", "ERROR"}, "ERROR"))
}
Bjorn is at 2
any long stay: true
longest: Astrid
trueIndexFunc returns -1 when nothing matches. MaxFunc is the longest booking that the generics lesson could not get from Max, and like slices.Max it panics on an empty slice: check len first with outside data.
A short function literal can sit on one line. Keep it to one line only when the body is one short expression, as here.
7. Sorted map keys
The slices and maps lesson collected map keys in a loop to sort them. maps.Keys and slices.Sorted do it in one line.
package main
import (
"fmt"
"maps"
"slices"
)
func main() {
counts := map[string]int{"WARNING": 1, "ERROR": 2, "INFO": 4}
for _, level := range slices.Sorted(maps.Keys(counts)) {
fmt.Printf("%-8s %d\n", level, counts[level])
}
}
ERROR 2
INFO 4
WARNING 1maps.Keys does not return a slice: it returns an iterator, a function that hands out the keys one at a time and can be used with range. slices.Sorted takes an iterator, collects it into a slice and sorts it. slices.Collect collects without sorting.
Iterators are how Go’s standard library offers sequences without building a slice first. You will use them through these functions far more often than you write one.
Generic methods
8. A method with its own type parameter
Since Go 1.27 a method can have type parameters of its own, after its name. Map turns a Page[T] into a Page[U] by calling a function on every item, so a page of bookings becomes a page of API responses with the same numbers.
package main
import "fmt"
type Page[T any] struct {
Items []T
Total int
}
// Map returns a page with the same numbers, whose items are f applied to each item.
func (p Page[T]) Map[U any](f func(T) U) Page[U] {
items := make([]U, 0, len(p.Items))
for _, item := range p.Items {
items = append(items, f(item))
}
return Page[U]{Items: items, Total: p.Total}
}
type Booking struct {
ID int
Guest string
Nights int
}
type BookingSummary struct {
ID int
Label string
}
func main() {
page := Page[Booking]{Items: []Booking{{1042, "Astrid", 3}, {1043, "Bjorn", 7}}, Total: 12}
summaries := page.Map(func(b Booking) BookingSummary {
return BookingSummary{ID: b.ID, Label: fmt.Sprintf("%s, %d nights", b.Guest, b.Nights)}
})
fmt.Printf("%T\n%+v\n", summaries, summaries)
}
main.Page[main.BookingSummary]
{Items:[{ID:1042 Label:Astrid, 3 nights} {ID:1043 Label:Bjorn, 7 nights}] Total:12}Go infers U from the function passed in: it returns a BookingSummary, so the result is a Page[BookingSummary]. Before Go 1.27 this had to be a plain function, MapPage(page, f), because methods could not add type parameters. It is Laravel’s $paginator->through(fn ($b) => …), with the result type known.
The Go team’s post Generic Methods explains the one limit: an interface cannot declare a generic method, so a generic method never counts when a type is checked against an interface.
Coming from PHP
<?php
usort($bookings, fn ($a, $b) => [$b->nights, $a->guest] <=> [$a->nights, $b->guest]);
$longest = collect($bookings)->sortByDesc('nights')->first();
$hasLongStay = collect($bookings)->contains(fn ($b) => $b->nights >= 7);
$next = 1042;
$nextId = function () use (&$next) { return $next++; };
Laravel collections and Go’s slices package cover the same ground. Collections chain lazily on any array; slices functions are plain calls on a typed slice, and each returns a typed result. There is no ->map()->filter()->values() chain in Go: you write the loop, or one call per step.
PHP closures copy the variables they use unless you add &. Go closures always share them, which is what made the old loop bug possible, and what makes the ID generator work.
PracticeA Tour of Go: function values and closures, one sort
In A Tour of Go, do Function values, Function closures and Exercise: Fibonacci closure.
Exercise: a survey ranking
Given type Result struct { Question string; Average float64; Answers int } and five results, sort them by average from the highest, then by number of answers from the highest, then by question. Then print the question with the most answers using slices.MaxFunc, and whether any average is below 2.5 using slices.ContainsFunc.
Remember
- A closure shares the variables it uses; give each closure its own value by making it in a function that takes the value as a parameter.
- Sort with
slices.SortFuncandcmp.Compare, and always end with a tie-breaker. - Get sorted map keys with
slices.Sorted(maps.Keys(m)).
Tomorrow is the build day: csv2json, 100K survey rows turned into JSON Lines, with every bad row reported, benchmarked against PHP.