What changed, 1.21 to 1.27
Your Go stopped at 1.20. This sheet lists each later change that matters, what it replaces, and where to learn it. Each entry links to its release note, and each rewrite is two programs that really ran.
- 1The go line in go.mod picks the language version. A newer toolchain with the old go line keeps the old behaviour.
- 2Five rewrites cover most code: min and max, range over int, slices and maps, WaitGroup.Go, and routing patterns.
- 3Delete the i := i copies. Each loop iteration has its own variables since 1.22.
- 4Run go fix after you raise the go line. It applies these rewrites for you.
//go:build go1.211
package main
import "fmt"
func main() {
var printers []func()
for i := 0; i < 3; i++ {
printers = append(printers, func() { fmt.Print(i, " ") })
}
for _, p := range printers {
p()
}
fmt.Println()
}- 1This line sets the language version of this file to 1.21. It is the only difference.
3 3 3package main
import "fmt"
func main() {
var printers []func()
for i := 01; i < 3; i++ {
printers = append(printers, func() { fmt.Print(i, " ") })
}
for _, p := range printers {
p()
}
fmt.Println()
}- 1Since 1.22 each iteration has a new i, so each closure holds its own.
0 1 2| what decides | set by | scope |
|---|---|---|
| Language version: features and loop rules | go line in go.mod | Each module; a //go:build line can change one file. |
| Library behaviour defaults, such as timer channels | go line, GODEBUG | The main module or workspace. |
| Which compiler and library run | GOTOOLCHAIN | The go command picks a toolchain at start. |
The same loop prints 3 3 3 at Go 1.21 and 0 1 2 at Go 1.22. The go line decides, so an upgrade is a choice I make per module.
| since | what changed | what it replaces | taught in |
|---|---|---|---|
| 1.21 | Built-ins min, max and clear. | Hand-written helpers and delete loops. | G2 Types and values |
| 1.21 | log/slog: structured logs with levels. | log.Printf with key=value text. | G14 Standard library tour |
| 1.21 | Packages slices, maps and cmp. | sort.Slice and hand-written loops. | G3 Slices, maps and strings inside |
| 1.21 | The go line is a strict minimum. The go command finds or downloads a newer toolchain. New toolchain line. | An advisory go line. | G8 Packages and modules |
| 1.22 | Each iteration of a for loop creates new variables. | The copy i := i before a closure. | G6 Iterators and closures |
| 1.22 | for i := range 10: a loop over an integer. | Three-part counting loops. | G2 Types and values |
| 1.22 | ServeMux patterns: methods, {id} wildcards and {$}. | Method checks and path parsing in each handler. | G16 HTTP |
| 1.23 | Range over iterator functions. | Callback visitors, and slices built only to loop once. | G6 Iterators and closures |
| 1.23 | Package iter, with iterators in slices and maps: Sorted, Collect, Keys, Values. | Loops that fill a slice, then sort it. | G6 Iterators and closures |
| 1.23 | Timers: an unstopped timer can be collected, and its channel is unbuffered. | Stop-and-drain code around Reset. | G11 Primitives |
| 1.24 | A type alias can have type parameters. | Defined types, which lose the methods. | G5 Generics |
| 1.24 | encoding/json tag option omitzero, which also honours an IsZero method. | Pointers to time.Time, and omitempty on structs. | G15 JSON |
| 1.24 | tool directives in go.mod, go get -tool, and go tool. | A tools.go file with blank imports. | G8 Packages and modules |
| 1.24 | Maps use Swiss Tables. With other work, CPU overhead falls 2 to 3% on average. | No code change. | G3 Slices, maps and strings inside |
| 1.25 | testing/synctest: a bubble with a fake clock. | Real sleeps and injected clocks in tests. | G20 Testing |
| 1.25 | sync.WaitGroup.Go. | wg.Add(1), go func, defer wg.Done(). | G11 Primitives |
| 1.25 | GOMAXPROCS follows the cgroup CPU limit on Linux and updates at run time. | A library that sets GOMAXPROCS at start. | G10 The runtime and scheduler |
| 1.26 | new takes an expression: new(30), new(f()). | A temporary variable, or a ptr[T] helper. | G2 Types and values |
| 1.26 | go fix is rebuilt around modernizers and //go:fix inline. | Manual upgrades to new idioms. | G23 Project shape |
| 1.26 | The Green Tea collector is the default: an expected 10 to 40% less collection overhead. | No code change. | G10 The runtime and scheduler |
| 1.27 | A method can declare its own type parameters. Interface methods cannot, and a generic method cannot implement one. | Package-level generic functions. | G5 Generics |
| 1.27 | encoding/json/v2 and jsontext. encoding/json now runs on the v2 implementation. | Nothing forced: v1 stays supported. | G15 JSON |
| 1.27 | The goroutineleak profile is generally available. | Reading goroutine dumps by eye. | G13 Races, deadlocks and leaks |
I can name the release of each change, and I know which sheet goes deeper.
| since | what changed | what it replaces | taught in |
|---|---|---|---|
| 1.21 | Built-ins min, max and clear. | Hand-written helpers and delete loops. | G2 Types and values |
| 1.21 | Package initialization order is specified: sort by import path, then take the first package that is ready. | An order the spec left undefined. | G8 Packages and modules |
| 1.21 | panic(nil) becomes a *runtime.PanicNilError, so recover in a panic never returns nil. | A panic that recover could not detect. | G7 Errors |
| 1.21 | Stronger type inference, also for generic functions passed as arguments. | Explicit type arguments. | G5 Generics |
| 1.22 | Each iteration of a for loop creates new variables. | The copy i := i before a closure. | G6 Iterators and closures |
| 1.22 | for i := range 10: a loop over an integer. | Three-part counting loops. | G2 Types and values |
| 1.23 | Range over iterator functions. | Callback visitors, and slices built only to loop once. | G6 Iterators and closures |
| 1.24 | A type alias can have type parameters. | Defined types, which lose the methods. | G5 Generics |
| 1.25 | No change for programs. The spec removes the term core types. | Nothing. | G5 Generics |
| 1.26 | new takes an expression: new(30), new(f()). | A temporary variable, or a ptr[T] helper. | G2 Types and values |
| 1.26 | A generic type can refer to itself in its type parameter list. | Constraints that could not name the type. | G5 Generics |
| 1.27 | A method can declare its own type parameters. Interface methods cannot, and a generic method cannot implement one. | Package-level generic functions. | G5 Generics |
| 1.27 | A struct literal key can be any valid field selector. | Top-level field names only. | G2 Types and values |
| 1.27 | Function type inference applies wherever a generic function is assigned or converted to a matching function type. | Explicit instantiation. | G5 Generics |
Most releases add one language feature. Two of them change how I write everyday loops.
| since | what changed | what it replaces | taught in |
|---|---|---|---|
| 1.21 | log/slog: structured logs with levels. | log.Printf with key=value text. | G14 Standard library tour |
| 1.21 | Packages slices, maps and cmp. | sort.Slice and hand-written loops. | G3 Slices, maps and strings inside |
| 1.21 | sync.OnceFunc, OnceValue and OnceValues. | A Once, a flag and result fields. | G11 Primitives |
| 1.21 | context.WithoutCancel, WithDeadlineCause, WithTimeoutCause and AfterFunc. | Custom context wrappers. | G11 Primitives |
| 1.22 | ServeMux patterns: methods, {id} wildcards and {$}. | Method checks and path parsing in each handler. | G16 HTTP |
| 1.22 | math/rand/v2: IntN, N, ChaCha8 and PCG. The top-level generator is always seeded at random. | math/rand and its Seed call. | G14 Standard library tour |
| 1.22 | cmp.Or, database/sql.Null[T], slices.Concat and reflect.TypeFor. | Default chains, NullString types, and append chains. | G14 Standard library tour |
| 1.22 | slices.Delete and its relatives zero the elements past the new length. | Stale pointers kept alive in the tail. | G3 Slices, maps and strings inside |
| 1.23 | Package iter, with iterators in slices and maps: Sorted, Collect, Keys, Values. | Loops that fill a slice, then sort it. | G6 Iterators and closures |
| 1.23 | Timers: an unstopped timer can be collected, and its channel is unbuffered. | Stop-and-drain code around Reset. | G11 Primitives |
| 1.23 | Package unique: canonical values and Handle[T]. | Hand-written interning. | G14 Standard library tour |
| 1.24 | encoding/json tag option omitzero, which also honours an IsZero method. | Pointers to time.Time, and omitempty on structs. | G15 JSON |
| 1.24 | os.Root: file operations that cannot leave one directory. | Path cleaning by hand. | G14 Standard library tour |
| 1.24 | testing.B.Loop. | for range b.N, with its reset timers. | G21 Performance |
| 1.24 | runtime.AddCleanup, and package weak. | runtime.SetFinalizer. | G21 Performance |
| 1.24 | strings.Lines, SplitSeq and FieldsSeq, with the same set in bytes. | strings.Split when the result is read once. | G14 Standard library tour |
| 1.24 | T.Context and T.Chdir in tests. | A context and a cleanup written by hand. | G20 Testing |
| 1.24 | New sync.Map implementation: writes to disjoint keys contend less. | The old sync.Map, with no code change. | G11 Primitives |
| 1.25 | testing/synctest: a bubble with a fake clock. | Real sleeps and injected clocks in tests. | G20 Testing |
| 1.25 | sync.WaitGroup.Go. | wg.Add(1), go func, defer wg.Done(). | G11 Primitives |
| 1.25 | http.CrossOriginProtection: CSRF checks with no tokens or cookies. | Token middleware. | G16 HTTP |
| 1.26 | errors.AsType, a generic errors.As. | A target variable for each errors.As. | G7 Errors |
| 1.26 | slog.NewMultiHandler. | A fan-out handler written by hand. | G14 Standard library tour |
| 1.26 | signal.NotifyContext cancels with a cause that names the signal. | A separate channel to learn the signal. | G11 Primitives |
| 1.26 | ServeMux trailing slash redirects use status 307, not 301. | Permanent redirects. | G16 HTTP |
| 1.26 | httputil.ReverseProxy.Director is deprecated. | Move to Rewrite. | G16 HTTP |
| 1.26 | io.ReadAll is often about 2 times faster, with about half the total memory. | The old io.ReadAll, with no code change. | G21 Performance |
| 1.26 | T.ArtifactDir, and B.Loop no longer blocks inlining in the loop body. | Test output in temporary folders. | G20 Testing |
| 1.27 | encoding/json/v2 and jsontext. encoding/json now runs on the v2 implementation. | Nothing forced: v1 stays supported. | G15 JSON |
| 1.27 | Package uuid generates and parses UUIDs. | A third-party UUID module. | G14 Standard library tour |
| 1.27 | strings.CutLast and bytes.CutLast. | strings.LastIndex with slicing. | G14 Standard library tour |
| 1.27 | synctest.Sleep, and httptest.NewTestServer on a fake network. | Sleep then Wait, and a real listener in a bubble. | G20 Testing |
| 1.27 | HTTP/1 Response.Body drains unread content on Close, up to a limit. | A drain with io.Copy before Close. | G16 HTTP |
Each new crypto package is in its release note: mlkem, hkdf, pbkdf2 and sha3 in 1.24, hpke in 1.26, mldsa in 1.27.
Logging, routing, UUIDs and slice helpers are in the standard library now, so a service needs fewer small dependencies.
| since | what changed | what it replaces | taught in |
|---|---|---|---|
| 1.21 | The go line is a strict minimum. The go command finds or downloads a newer toolchain. New toolchain line. | An advisory go line. | G8 Packages and modules |
| 1.21 | The go line of the main module picks GODEBUG defaults. | Behaviour that changed with the toolchain. | G8 Packages and modules |
| 1.21 | A default.pgo file in the main package turns on profile-guided optimization. | A manual -pgo flag. | G21 Performance |
| 1.22 | go work vendor: a vendor folder for a workspace. | No vendoring in a workspace. | G8 Packages and modules |
| 1.22 | go vet stops the old loop variable report on 1.22 files. It adds checks on append, defer time.Since and slog pairs. | Reports that no longer apply. | G23 Project shape |
| 1.23 | go mod tidy -diff, and go env -changed. | Run tidy, then git diff. | G8 Packages and modules |
| 1.23 | godebug block in go.mod and go.work. | A //go:debug line in a main package. | G8 Packages and modules |
| 1.23 | go vet stdversion: symbols too new for the go line. | A failure on an older toolchain. | G8 Packages and modules |
| 1.23 | Go telemetry: local counters, and upload only after go telemetry on. | Nothing. | G23 Project shape |
| 1.24 | tool directives in go.mod, go get -tool, and go tool. | A tools.go file with blank imports. | G8 Packages and modules |
| 1.24 | go build -json, and the main module version from the VCS tag in the binary. | Parsed text output, and ldflags stamps. | G23 Project shape |
| 1.24 | GOAUTH authenticates private module fetches. | Credentials only in .netrc or Git. | G8 Packages and modules |
| 1.24 | go vet tests analyzer, and a report on fmt.Printf(s) with a non-constant s. | Mistakes found at run time. | G20 Testing |
| 1.25 | ignore directive in go.mod, and the work package pattern. | Underscore prefixes on folders. | G8 Packages and modules |
| 1.25 | A go line update no longer adds a toolchain line. | Unwanted toolchain lines in diffs. | G8 Packages and modules |
| 1.25 | go vet waitgroup and hostport analyzers. | Misplaced Add, and IPv4-only address strings. | G13 Races, deadlocks and leaks |
| 1.25 | go doc -http. | A separate documentation server. | G23 Project shape |
| 1.26 | go fix is rebuilt around modernizers and //go:fix inline. | Manual upgrades to new idioms. | G23 Project shape |
| 1.26 | go mod init writes the previous release in the go line. | New modules that require the newest release. | G8 Packages and modules |
| 1.26 | pprof web UI opens on the flame graph. | The graph view as the default. | G21 Performance |
| 1.27 | go test runs the stdversion check by default. | go vet as a separate step for this check. | G20 Testing |
| 1.27 | go mod tidy keeps two require blocks: direct and indirect. | Scattered require blocks. | G8 Packages and modules |
| 1.27 | go doc takes pkg@version, and -ex lists examples. | A checkout of that version. | G23 Project shape |
| 1.27 | go vet reports %w with a pointer to an error type. | Wrapped errors that errors.Is misses. | G7 Errors |
| 1.27 | The go command fails on a removed GODEBUG setting with an old value. | A setting that stayed after its support ended. | G8 Packages and modules |
Tools now live in go.mod, and go fix brings old code up to the current idioms.
| since | what changed | what it replaces | taught in |
|---|---|---|---|
| 1.21 | Garbage collector tuning: up to 40% less tail latency in some programs. | No code change. | G21 Performance |
| 1.22 | Type metadata sits nearer to heap objects: 1 to 3% less CPU, about 1% less memory. | No code change. | G21 Performance |
| 1.22 | The execution tracer is rebuilt. | Traces that were costly to start and stop. | G21 Performance |
| 1.24 | Maps use Swiss Tables. With other work, CPU overhead falls 2 to 3% on average. | No code change. | G3 Slices, maps and strings inside |
| 1.25 | GOMAXPROCS follows the cgroup CPU limit on Linux and updates at run time. | A library that sets GOMAXPROCS at start. | G10 The runtime and scheduler |
| 1.25 | runtime/trace.FlightRecorder keeps recent trace data in memory. | Full traces, which were too costly to keep on. | G21 Performance |
| 1.25 | A compiler fix: a use of a nil result before the error check now panics. | Programs that worked by a compiler bug from 1.21 to 1.24. | G7 Errors |
| 1.25 | The compiler puts slice backing stores on the stack in more cases. | No code change. | G21 Performance |
| 1.26 | The Green Tea collector is the default: an expected 10 to 40% less collection overhead. | No code change. | G10 The runtime and scheduler |
| 1.26 | Baseline cgo call overhead falls about 30%. | No code change. | G21 Performance |
| 1.26 | The heap base address is random at start on 64-bit platforms. | A fixed base. | G22 Reflection and unsafe |
| 1.27 | The goroutineleak profile is generally available. | Reading goroutine dumps by eye. | G13 Races, deadlocks and leaks |
| 1.27 | Size-specialized allocation: up to 30% cheaper for some objects under 80 bytes, about 1% in real programs. | No code change. | G21 Performance |
| 1.27 | Tracebacks show goroutine labels when the go line is 1.27 or later. | Finding the request by hand. | G10 The runtime and scheduler |
| 1.27 | The asynctimerchan setting is gone, so timer channels are always unbuffered. | A GODEBUG opt-out. | G11 Primitives |
Most runtime gains need no code change. The one that changes my deploy is GOMAXPROCS, which now reads the container limit.
package main
import (
"fmt"
"math"
)
func smaller(a, b int) int {
if a < b {
return a
}
return b
}
func main() {
fmt.Println(smaller(smaller(7, 3), 5))
m := map[float64]string{1: "one", math.NaN(): "nan"}
for k := range m {
delete(m, k)1
}
fmt.Println("left in map:", len(m))
s := []int{1, 2, 3}
for i := range s {
s[i] = 0
}
fmt.Println(s)
}- 1The NaN key is not equal to itself, so delete finds nothing. One entry stays.
3
left in map: 1
[0 0 0]package main
import (
"fmt"
"math"
)
func main() {
fmt.Println(min(7, 3, 5)1, max(2.5, 1), min("b", "a"))
m := map[float64]string{1: "one", math.NaN(): "nan"}
clear(m)2
fmt.Println("left in map:", len(m))
s := []int{1, 2, 3}
clear(s)3
fmt.Println(s)
}- 1Built-ins take any number of arguments of an ordered type.
- 2Removes every entry, also a NaN key.
- 3Sets every element to zero. The length stays.
3 2.5 a
left in map: 0
[0 0 0]clear empties a map even when it holds a NaN key. A delete loop cannot remove that key, because NaN is not equal to itself.
package main
import "fmt"
func main() {
for i := 0; i < 3; i++ {
fmt.Print(i, " ")
}
fmt.Println()
for i := 0; i < 2; i++ {
fmt.Print("retry ")
}
fmt.Println()
}0 1 2
retry retrypackage main
import "fmt"
func main() {
for i := range 3 {
fmt.Print(i, " ")
}
fmt.Println()
for range 21 {
fmt.Print("retry ")
}
fmt.Println()
}- 1Drop the variable when the loop needs only a count.
0 1 2
retry retryfor range n says that I want n rounds and no index.
package main
import "fmt"
type Tree struct {
Left, Right *Tree
Val int
}
// Walk calls visit in order until visit returns false.
func (t *Tree) Walk(visit func(int) bool) bool {
if t == nil {
return true
}
return t.Left.Walk(visit) && visit(t.Val) && t.Right.Walk(visit)
}
func main() {
t := &Tree{&Tree{Val: 1}, &Tree{Val: 3}, 2}
t.Walk(func(v int) bool {
if v == 3 {
return false1
}
fmt.Print(v, " ")
return true
})
fmt.Println()
}- 1Stop means a return value. The caller cannot use break or return here.
1 2package main
import (
"fmt"
"iter"
)
type Tree struct {
Left, Right *Tree
Val int
}
// All yields the values in order.
func (t *Tree) All() iter.Seq[int]1 {
return func(yield func(int) bool) {
t.push(yield)
}
}
func (t *Tree) push(yield func(int) bool) bool {
if t == nil {
return true
}
return t.Left.push(yield) && yield(t.Val) && t.Right.push(yield)
}
func main() {
t := &Tree{&Tree{Val: 1}, &Tree{Val: 3}, 2}
for v := range t.All() {
if v == 3 {
break2
}
fmt.Print(v, " ")
}
fmt.Println()
}- 1A named form of func(yield func(int) bool).
- 2yield returns false, and the iterator stops.
1 2An iterator is a function that takes yield. The caller writes a normal loop, and a break reaches the iterator as a false result.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
)
func item(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
id := strings.TrimPrefix(r.URL.Path, "/items/")1
fmt.Fprint(w, "item "+id)
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/items/", item)
for _, req := range [][2]string{
{"GET", "/items/42"},
{"POST", "/items/42"},
{"GET", "/items/42/extra"},
} {
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, httptest.NewRequest(req[0], req[1], nil))
fmt.Println(req[0], req[1], rec.Code, rec.Body)
}
}- 1The prefix pattern also accepts /items/42/extra, and the id is wrong.
GET /items/42 200 item 42
POST /items/42 405
GET /items/42/extra 200 item 42/extrapackage main
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
)
func item(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "item "+r.PathValue("id")2)
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /items/{id}"1, item)
for _, req := range [][2]string{
{"GET", "/items/42"},
{"POST", "/items/42"},
{"GET", "/items/42/extra"},
} {
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, httptest.NewRequest(req[0], req[1], nil))
body := strings.TrimSpace(rec.Body.String())
fmt.Println(req[0], req[1], rec.Code, body)
}
}- 1The method and one path segment are in the pattern. GET also registers HEAD.
- 2Reads the wildcard.
GET /items/42 200 item 42
POST /items/42 405 Method Not Allowed
GET /items/42/extra 404 404 page not foundI put the method and the wildcard in the pattern. ServeMux then gives me 405 and an Allow header, and I drop the router library for simple services.
package main
import (
"log"
"os"
)
func main() {
logger := log.New(os.Stdout, "", 0)
order, user := 1042, "u7"
logger.Printf1("order=%d user=%s msg=%q", order, user, "paid in full")
logger.Printf("order=%d user=%s retries=%d", order, user, 2)
}- 1Every call repeats the fields, and a log tool must parse the text.
order=1042 user=u7 msg="paid in full"
order=1042 user=u7 retries=2package main
import (
"log/slog"
"os"
)
func noTime(_ []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey {
return slog.Attr{}
}
return a
}
func main() {
opts := &slog.HandlerOptions{ReplaceAttr: noTime3}
logger := slog.New(slog.NewJSONHandler(os.Stdout, opts))
req := logger.With("order", 1042, "user", "u7")1
req.Info("paid in full")
req.Warn("gateway slow", "retries", 2)
req.Debug2("this level is off")
}- 1Each line from req carries these fields.
- 2The default level is Info, so this line prints nothing.
- 3Only here so that the recorded output has no clock.
{"level":"INFO","msg":"paid in full","order":1042,"user":"u7"}
{"level":"WARN","msg":"gateway slow","order":1042,"user":"u7","retries":2}I log with slog, attach the request fields once with With, and let the handler choose the format.
package main
import (
"fmt"
"sort"
)
func main() {
stock := map[string]int{"pear": 2, "apple": 5, "fig": 9}
keys := make([]string, 0, len(stock))
for k := range stock {
keys = append(keys, k)
}
sort.Strings(keys)
fmt.Println(keys)
found := false
for _, k := range keys {
if k == "fig" {
found = true
break
}
}
fmt.Println(found)
copied := make(map[string]int, len(stock))
for k, v := range stock {
copied[k] = v
}
fmt.Println(len(copied))
}[apple fig pear]
true
3package main
import (
"fmt"
"maps"
"slices"
)
func main() {
stock := map[string]int{"pear": 2, "apple": 5, "fig": 9}
keys := slices.Sorted(maps.Keys(stock))1
fmt.Println(keys)
fmt.Println(slices.Contains(keys, "fig"))
copied := maps.Clone(stock)2
fmt.Println(len(copied))
}- 1maps.Keys returns an iterator. slices.Sorted collects it and sorts.
- 2A shallow copy.
[apple fig pear]
true
3slices.Sorted(maps.Keys(m)) is one line, and it replaces a loop, an append and a sort.
package main
import "fmt"
type Tree[K comparable, V any] struct{ items map[K]V }
func New[K comparable, V any]() Tree[K, V] {
return Tree[K, V]{items: map[K]V{}}
}
func (t Tree[K, V]) Put(k K, v V) { t.items[k] = v }
// A defined type: it drops every method of Tree.
type ByName[V any] Tree[string, V]1
func main() {
names := ByName[int](New[string, int]())
Tree[string, int](names).Put("a", 1) // needs a conversion
fmt.Printf("%T %d\n", names, len(names.items))
}- 1A defined type is a new type. It has no methods from Tree.
main.ByName[int] 1package main
import "fmt"
type Tree[K comparable, V any] struct{ items map[K]V }
func New[K comparable, V any]() Tree[K, V] {
return Tree[K, V]{items: map[K]V{}}
}
func (t Tree[K, V]) Put(k K, v V) { t.items[k] = v }
// An alias: the same type under a shorter name.
type ByName[V any] = Tree[string, V]1
func main() {
var names ByName[int] = New[string, int]()
names.Put("a", 1) // the methods stay
fmt.Printf("%T %d\n", names, len(names.items))
}- 1The = makes an alias, and %T prints the real type.
main.Tree[string,int] 1A generic alias keeps the type and its methods, so I can move a type between packages one step at a time.
package main
import (
"encoding/json"
"fmt"
"time"
)
type Task struct {
Name string `json:"name"`
Due time.Time `json:"due,omitempty"`1
Done *time.Time `json:"done,omitempty"`2
}
func main() {
b, err := json.Marshal(Task{Name: "ship"})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(b))
}- 1omitempty has no effect on a struct.
- 2The old fix: a pointer, only to get nil.
{"name":"ship","due":"0001-01-01T00:00:00Z"}package main
import (
"encoding/json"
"fmt"
"time"
)
type Task struct {
Name string `json:"name"`
Due time.Time `json:"due,omitzero1"`
Done time.Time `json:"done,omitzero"`
}
func main() {
b, err := json.Marshal(Task{Name: "ship"})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(b))
}- 1Uses the IsZero method when the type has one, as time.Time does.
{"name":"ship"}omitempty never removes a struct, so a zero time.Time prints as year 1. omitzero removes it.
package main
import (
"fmt"
"time"
)
// expires reports on done when ttl has passed.
func expires(ttl time.Duration, done chan<- string) {
time.Sleep(ttl)
done <- "expired"
}
func main() {
const ttl = 300 * time.Millisecond
start := time.Now()
done := make(chan string, 1)
go expires(ttl, done)
time.Sleep(ttl + 50*time.Millisecond)1 // wait, and hope
select {
case v := <-done:
fmt.Println(v)
default:
fmt.Println("too early")
}
fmt.Println("real wait >= ttl:", time.Since(start) >= ttl)
}- 1A real wait. Too short is flaky, and too long is slow.
expired
real wait >= ttl: truepackage main
import (
"fmt"
"testing"
"testing/synctest"
"time"
)
func expires(ttl time.Duration, done chan<- string) {
time.Sleep(ttl)
done <- "expired"
}
func testExpiry(t *testing.T) {
wall := time.Now()
synctest.Test1(t, func(t *testing.T) {
const ttl = time.Hour
start := time.Now()
done := make(chan string, 1)
go expires(ttl, done)
time.Sleep(ttl) // the fake clock jumps
synctest.Wait()2 // until expires has blocked or exited
fmt.Println(<-done)
fmt.Println("fake time:", time.Since(start))
})
fmt.Println("real wait < 1s:", time.Since(wall) < time.Second)
}
func main() {
testing.Main3(
func(string, string) (bool, error) { return true, nil },
[]testing.InternalTest{{Name: "Expiry", F: testExpiry}},
nil, nil,
)
}- 1Starts a bubble with a fake clock.
- 2Returns when every other goroutine in the bubble is blocked or finished.
- 3Only here so that a plain program can run a test. Normal code uses go test.
expired
fake time: 1h0m0s
real wait < 1s: true
PASSIn a synctest bubble, an hour passes at once, because the clock jumps when every goroutine in the bubble blocks.
package main
import (
"fmt"
"sync"
"sync/atomic"
)
func main() {
var wg sync.WaitGroup
var sum atomic.Int64
for i := range 4 {
wg.Add(1)1
go func() {
defer wg.Done()
sum.Add(int64(i))
}()
}
wg.Wait()
fmt.Println(sum.Load())
}- 1Must run before the go statement. go vet reports a misplaced Add since 1.25.
6package main
import (
"fmt"
"sync"
"sync/atomic"
)
func main() {
var wg sync.WaitGroup
var sum atomic.Int64
for i := range 4 {
wg.Go(1func() { sum.Add(int64(i)) })
}
wg.Wait()
fmt.Println(sum.Load())
}- 1Adds 1, starts the goroutine, and calls Done when the function returns.
6wg.Go does the Add and the Done, so I cannot put the Add in the wrong place.
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age *int `json:"age,omitempty"` // nil means unknown
}
func ptr[T any](v T) *T { return &v }1
func years(born, now int) int { return now - born }
func main() {
age := years(1990, 2026) // a variable for one address
a, _ := json.Marshal(Person{"Ana", &age})
b, _ := json.Marshal(Person{"Bo", ptr(years(2001, 2026))})
c, _ := json.Marshal(Person{Name: "Cy"})
fmt.Printf("%s\n%s\n%s\n", a, b, c)
}- 1Most projects carried this helper.
{"name":"Ana","age":36}
{"name":"Bo","age":25}
{"name":"Cy"}package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string `json:"name"`
Age *int `json:"age,omitempty"` // nil means unknown
}
func years(born, now int) int { return now - born }
func main() {
a, _ := json.Marshal(Person{"Ana", new(years(1990, 2026))1})
b, _ := json.Marshal(Person{"Bo", new(25)})
c, _ := json.Marshal(Person{Name: "Cy"})
fmt.Printf("%s\n%s\n%s\n", a, b, c)
}- 1A new variable holds the result of the expression.
{"name":"Ana","age":36}
{"name":"Bo","age":25}
{"name":"Cy"}new(expr) gives me a pointer to a value in one expression, which suits optional fields in JSON and protobuf.
package main
import (
"fmt"
"strconv"
)
type List[T any] []T
func (l List[T]) Keep(f func(T) bool) List[T] {
var out List[T]
for _, v := range l {
if f(v) {
out = append(out, v)
}
}
return out
}
// A method could not add a type parameter, so this stays a function.
func Map[T, U any](l List[T], f func(T) U) List[U] {
out := make(List[U], 0, len(l))
for _, v := range l {
out = append(out, f(v))
}
return out
}
func main() {
nums := List[int]{1, 2, 3, 4}
even := func(n int) bool { return n%2 == 0 }
fmt.Printf("%q\n", Map(nums.Keep(even), strconv.Itoa)1)
}- 1The function wraps the chain, so it reads inside out.
["2" "4"]package main
import (
"fmt"
"strconv"
)
type List[T any] []T
func (l List[T]) Keep(f func(T) bool) List[T] {
var out List[T]
for _, v := range l {
if f(v) {
out = append(out, v)
}
}
return out
}
// The method declares its own type parameter U.
func (l List[T]) Map[U any]1(f func(T) U) List[U] {
out := make(List[U], 0, len(l))
for _, v := range l {
out = append(out, f(v))
}
return out
}
func main() {
nums := List[int]{1, 2, 3, 4}
even := func(n int) bool { return n%2 == 0 }
fmt.Printf("%q\n", nums.Keep(even).Map(strconv.Itoa)2)
}- 1U belongs to this method. T comes from the receiver.
- 2U is inferred from the argument.
["2" "4"]A method can now declare a type parameter, so calls chain left to right. Interfaces still cannot have generic methods.
package main
import (
"errors"
"fmt"
"runtime"
"time"
)
var stop = make(chan struct{})
func worker() { <-stop } // waits on a global: healthy
func first(jobs int) error {
ch := make(chan error) // no buffer
for range jobs {
go func() { ch <- errors.New("failed") }()
}
return <-ch // one read, then the other jobs block for good
}
func main() {
for range 2 {
go worker()
}
if err := first(3); err == nil {
panic("no error")
}
time.Sleep(50 * time.Millisecond)
fmt.Println("goroutines:", runtime.NumGoroutine()1)
}- 1A count of all goroutines. It cannot tell a parked worker from a leak.
goroutines: 5package main
import (
"bytes"
"errors"
"fmt"
"regexp"
"runtime/pprof"
"time"
)
var stop = make(chan struct{})
func worker() { <-stop } // waits on a global: healthy
func first(jobs int) error {
ch := make(chan error) // no buffer
for range jobs {
go func() { ch <- errors.New("failed") }()
}
return <-ch // one read, then the other jobs block for good
}
func main() {
for range 2 {
go worker()
}
if err := first(3); err == nil {
panic("no error")
}
time.Sleep(50 * time.Millisecond)
var buf bytes.Buffer
p := pprof.Lookup("goroutineleak")1
if err := p.WriteTo(&buf, 1)2; err != nil { // runs the detection
panic(err)
}
fmt.Println("leaked:", p.Count())
at := regexp.MustCompile(`main\.first\.func1`).Find(buf.Bytes())
fmt.Printf("blocked in: %s\n", at)
}- 1Also served at /debug/pprof/goroutineleak.
- 2The collector finds blocked goroutines whose channel no running goroutine can reach.
leaked: 2
blocked in: main.first.func1The workers wait on a global, which stays reachable, so the profile does not report them. For the same reason it cannot report a leak on a global channel.
The goroutine count says 5, and that mixes healthy and leaked. The leak profile says 2, and it names the function.
| when | the moment | what to do or say | status |
|---|---|---|---|
| build | Routes for a small API. | Use ServeMux patterns with a method and a wildcard. | Approved |
| build | Stable output from a map. | Use slices.Sorted(maps.Keys(m)). | Approved |
| build | Fan out in a test. | Use wg.Go. Drop i := i inside the loop. | Approved |
| build | An optional field in a response. | Use new(expr) for a pointer, and omitzero for a time. | Approved |
| build | A TTL needs a test. | Use synctest, with no real sleep. | Approved |
| talk | "How do you upgrade Go in a large repo?" | Raise the go line per module, read the GODEBUG changes, run go fix, then run the tests with -race. | Approved |
| talk | "How does this run in a container?" | Since 1.25, GOMAXPROCS follows the cgroup CPU limit on Linux. A CPU request has no effect on it. | Approved |
| talk | "Could this code leak goroutines?" | Name what stops each goroutine, then cite the goroutineleak profile. | Approved |
| talk | "Should we move to encoding/json/v2?" | No need to hurry. V1 stays supported and now runs on the v2 code. Note that v2 rejects duplicate names. | Test the strict defaults |
I write current Go by habit, and I can say which release gave me each feature.
0 of 12 known
Predict the output.
package main import ( "fmt" "math" ) func main() { fmt.Println(min(1.0, math.NaN(), 3.0)) fmt.Println(max(1, 2.5)) var s []int clear(s) fmt.Println(s == nil) }Predict the output. The body changes i, and a new i starts each iteration.
package main import "fmt" func main() { var ps []*int for i := 0; i < 3; i++ { ps = append(ps, &i) i++ } for _, p := range ps { fmt.Print(*p, " ") } fmt.Println(len(ps)) }Predict the output. The body assigns to n.
package main import "fmt" func main() { n := 3 for i := range n { n = 10 fmt.Print(i, " ") } fmt.Println() for i := range uint8(2) { fmt.Printf("%T ", i) } fmt.Println() for range -1 { fmt.Println("never") } fmt.Println("done") }Predict the output.
package main import ( "fmt" "slices" ) func main() { func() { for v := range slices.Values([]int{1, 2}) { defer fmt.Println("deferred", v) fmt.Println("body", v) } fmt.Println("after loop") }() fmt.Println("after func") }Predict the output. The iterator ignores the result of yield.
package main import "fmt" // bad ignores the false that yield returns after a break. func bad(yield func(int) bool) { yield(1) yield(2) } func main() { defer func() { fmt.Println("recovered:", recover()) }() for v := range bad { fmt.Println(v) break } }Predict the output of each request.
package main import ( "fmt" "net/http" "net/http/httptest" ) func name(s string) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, s, " ", r.PathValue("rest")) } } func main() { mux := http.NewServeMux() mux.Handle("/files/{rest...}", name("wild")) mux.Handle("GET /files/new", name("exact")) mux.Handle("/{$}", name("root")) for _, r := range [][2]string{ {"HEAD", "/files/new"}, {"POST", "/files/new"}, {"GET", "/files/a/b"}, {"GET", "/"}, {"GET", "/other"}, } { rec := httptest.NewRecorder() mux.ServeHTTP(rec, httptest.NewRequest(r[0], r[1], nil)) fmt.Printf("%s %s: %d %s", r[0], r[1], rec.Code, rec.Body) fmt.Println() } }Predict the output. Both patterns match the path /items/new.
package main import ( "fmt" "net/http" "strings" ) func main() { defer func() { msg := fmt.Sprint(recover()) first, _, _ := strings.Cut(msg, " (registered") fmt.Println("conflict:", strings.Contains(msg, "conflicts"), first) }() mux := http.NewServeMux() ok := func(http.ResponseWriter, *http.Request) {} mux.HandleFunc("/items/{id}", ok) mux.HandleFunc("/{kind}/new", ok) fmt.Println("no conflict") }Predict the output. A and B are empty slices that are not nil.
package main import ( "encoding/json" "fmt" ) type Inner struct{ N int } type T struct { A []int `json:"a,omitempty"` B []int `json:"b,omitzero"` C Inner `json:"c,omitempty"` D Inner `json:"d,omitzero"` E int `json:"e,omitempty,omitzero"` } func main() { b, err := json.Marshal(T{A: []int{}, B: []int{}}) fmt.Println(string(b), err) }Predict the output.
package main import "fmt" func main() { defer func() { r := recover() fmt.Printf("%T\n", r) fmt.Println(r != nil) }() panic(nil) }Predict the output.
package main import "fmt" func main() { x := 1 p := new(x) x = 2 q := new(int64(*p)) fmt.Println(*p, *q, p == new(1)) fmt.Printf("%T %T\n", p, q) }Predict the output. The backing array is shared.
package main import ( "fmt" "slices" ) func main() { s := []int{1, 2, 3, 4} t := slices.Delete(s, 0, 2) fmt.Println(t, s) fmt.Println(slices.Repeat([]int{1}, 3), slices.Concat(t, t)) }Predict the output.
package main import "fmt" type Set[T comparable] = map[T]struct{} func size(m map[string]struct{}) int { return len(m) } func main() { s := Set[string]{"a": {}} fmt.Println(size(s)) fmt.Printf("%T\n", s) }