Skip to content
Tutorials Center
My learning

Topics

Lesson 128 of 147 ยท Advanced Go

What's New in Go 1.21 to 1.27

A release-by-release tour of Go 1.21 to 1.27 with runnable examples - built-ins, loop variables, iterators, generic aliases, WaitGroup.Go, new(expr), generic methods, json/v2 and GODEBUG.

Go ships a new version every six months, and since 2023 those releases have been unusually rich. Between Go 1.21 and Go 1.27 the language gained built-in min and max, loop variables that behave sensibly, ranging over integers and functions, generic type aliases, new(expr), and methods with their own type parameters. The standard library gained log/slog, slices, maps, math/rand/v2, os.Root, testing/synctest and a second JSON package.

This lesson walks through the headline changes release by release. Every section has a runnable example, and every example was compiled and run on Go 1.27.3, the version this course teaches. Use it two ways: as a map of what modern Go looks like if you learned the language years ago, and as an upgrade checklist for old code. The details of each feature live in the lessons linked along the way.

A feature belongs to the version where it was added, and your go.mod decides whether a language feature is allowed. A module whose go.mod says go 1.21 cannot use for i := range 10, even when you build it with a newer toolchain. Library additions are different: they are available whenever the toolchain is new enough.

Go 1.21: built-ins, new packages and slog

Go 1.21 (August 2023) is the release that made generic code feel at home in the standard library.

  • Built-in functions min, max and clear. min and max accept any ordered type and any number of arguments; clear empties a map or zeroes every element of a slice.
  • New packages slices, maps and cmp with generic helpers for sorting, searching and comparing. See the slices and maps packages.
  • log/slog, structured logging with levels, attributes and pluggable handlers. See logging.
  • sync.OnceFunc, OnceValue and OnceValues, which wrap a function so it runs once and remembers its result.
  • context.WithoutCancel, AfterFunc and WithTimeoutCause, plus errors.ErrUnsupported.
  • Toolchain management: the go line in go.mod became a strict minimum, a toolchain line was added, and the go command can download the Go version a module asks for (GOTOOLCHAIN). See Go modules.
  • panic(nil) changed: it now panics with a *runtime.PanicNilError, so recover() never returns nil for a real panic.
Go Go 1.21: min, max, clear, slices and OnceValue

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The sort puts the highest score first and breaks ties by name. cmp.Or, which returns its first non-zero argument, arrived in Go 1.22 and is a neat way to chain comparisons, as you can see. The function passed to OnceValue ran a single time even though it was called twice.

Go 1.22: loop variables, range over int and rand/v2

Go 1.22 (February 2024) fixed the most famous trap in the language.

  • Per-iteration loop variables. Each iteration of a for loop gets its own copy of the variable, so closures and goroutines started inside the loop capture the value of that iteration. This applies to modules whose go.mod says go 1.22 or later.
  • Range over integers: for i := range 5 counts from 0 to 4. See for loops.
  • Enhanced net/http.ServeMux: patterns can include a method and wildcards, such as GET /items/{id}. See REST APIs.
  • math/rand/v2, the first "v2" package in the standard library, with cleaner names (IntN, N), better generators and no global seed to manage. See math and random numbers.
  • Small additions: slices.Concat, cmp.Or, reflect.TypeFor, and database/sql.Null[T].
Go Go 1.22: fresh loop variables and range over int

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Before Go 1.22 the first loop printed 3 3 3, because all three closures shared one variable that ended at 3. With the new rule they print 0 1 2. The random numbers are repeatable because the generator was created with a fixed seed. rand.New(rand.NewPCG(1, 2)) always produces the same sequence, while the top-level functions such as rand.IntN are seeded randomly.

Go 1.23: iterators, unique and timer changes

Go 1.23 (August 2024) added range over functions, the biggest language change since generics.

  • Iterators. A function of type func(yield func(V) bool) can be used directly in a for range loop. The new iter package names the two common shapes, iter.Seq[V] and iter.Seq2[K, V]. See iterators.
  • Iterator helpers in the library: slices.Values, slices.All, slices.Collect, slices.Sorted, slices.Chunk, maps.Keys, maps.Values and maps.Collect. The functions maps.Keys and maps.Values now return iterators rather than slices.
  • unique: canonicalize ("intern") comparable values so equal values share one copy and compare with a single pointer comparison.
  • Timers and tickers were reworked. Their channels became unbuffered, and unreferenced timers can be garbage-collected even if you never stop them. Stale values are no longer delivered after Reset or Stop.
  • structs.HostLayout and an opt-in telemetry system for the go command (off by default).
Go Go 1.23: writing and consuming iterators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The break inside the loop makes yield return false, which tells Countdown to stop. That contract is why a range-over-func loop can exit early without leaking anything.

Go 1.24: generic aliases, os.Root and string iterators

Go 1.24 (February 2025) finished a few long-running generics projects and tightened security.

  • Generic type aliases: type Set[T comparable] = map[T]struct{}. See generic types.
  • os.Root, created with os.OpenRoot(dir), gives file access that cannot escape the directory, even through .. or symbolic links. See files and paths.
  • String and bytes iterators: strings.Lines, SplitSeq, SplitAfterSeq, FieldsSeq and FieldsFuncSeq produce pieces lazily, without allocating a slice.
  • omitzero for encoding/json struct tags, which finally works for time.Time and other structs.
  • testing.B.Loop, a simpler and more reliable way to write benchmark loops, and T.Context.
  • weak pointers and runtime.AddCleanup, a better alternative to finalizers.
  • Faster maps: the built-in map moved to a Swiss-table implementation. Your code stays the same, but lookups and inserts got cheaper.
  • tool directives in go.mod to track developer tools such as code generators, plus new crypto/sha3, crypto/mlkem and a few other crypto packages.
Go Go 1.24: generic aliases, string iterators and omitzero

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

With the old omitempty the zero time.Time would have appeared in the JSON as "0001-01-01T00:00:00Z". omitzero leaves it out. We check only result.N > 0 for the benchmark because timings differ on every machine.

os.Root deserves its own demonstration, since it closes a whole class of path-traversal bugs.

Go Go 1.24: os.Root refuses to leave its directory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The second read fails with path escapes from parent, no matter how the path is spelled. Method names such as ReadFile were added to Root in later releases; in Go 1.24 itself you would call root.Open and read from the returned file.

Go 1.25: WaitGroup.Go, synctest and a smarter runtime

Go 1.25 (August 2025) was a quieter language release but a big one for concurrency.

  • sync.WaitGroup.Go starts a goroutine and does the Add(1) and Done() bookkeeping for you. See the sync package.
  • testing/synctest graduated from an experiment. synctest.Test runs code in a "bubble" with a fake clock, so tests with timers run instantly and deterministically. See testing concurrent code.
  • Container-aware GOMAXPROCS: on Linux the runtime now respects CPU limits set by cgroups, and adjusts if they change. That fixes a classic problem where a Go service in a container with a 2-CPU limit used the host's 64 cores for scheduling and got throttled.
  • Experiments: a new garbage collector design ("Green Tea") and the new JSON package were available behind GOEXPERIMENT flags.
  • New diagnostics: runtime/trace.FlightRecorder keeps a rolling trace in memory that you can save after something goes wrong, and go vet learned to catch misuse of WaitGroup and net.JoinHostPort.
  • Language spec cleanup: the "core types" concept was removed from the spec. It changes nothing in practice but makes generics easier to explain.
Go Go 1.25: sync.WaitGroup.Go

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Compare this with the older recipe of wg.Add(1), go func() { defer wg.Done(); ... }(). There is no way to forget Done now. The program prints the results in index order, because the map is read after Wait in a fixed order; the goroutines themselves run in no particular order.

A synctest test looks like this. It is read-only here because it needs go test:

Go
func TestRetryWaits(t *testing.T) {
	synctest.Test(t, func(t *testing.T) {
		start := time.Now()
		time.Sleep(24 * time.Hour) // returns instantly: the bubble's clock jumps ahead
		if got := time.Since(start); got != 24*time.Hour {
			t.Fatalf("elapsed %v", got)
		}
	})
}

Go 1.26: new(expr), AsType and self-referential constraints

Go 1.26 (February 2026) made everyday code a little shorter.

  • new(expr): the operand of new can be a value, so new(42) or new(time.Now()) allocates and initializes in one step. See pointers.
  • Self-referential type constraints: a generic type may mention itself in its own constraint, for example type Node[N Node[N]] interface{ Next() N }.
  • errors.AsType[T], a generic, type-safe replacement for errors.As. See wrapping errors.
  • Reflection iterators: reflect.Type.Fields() and Methods() return iterators.
  • slog.NewMultiHandler sends each log record to several handlers; bytes.Buffer.Peek looks at upcoming bytes without consuming them.
  • Runtime: the Green Tea garbage collector became the default, and calls from Go to C code (cgo) got cheaper.
  • go fix was rebuilt on the same analysis framework as go vet. It now contains "modernizers" that rewrite old code to newer idioms, such as replacing hand-written loops with slices helpers or min and max. Running it after each upgrade is a cheap way to adopt new features.
Go Go 1.26: new(expr), errors.AsType and reflect iterators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The Node[N Node[N]] constraint says: "N is a type whose Next method returns another N". That is the shape you need for linked structures, trees and fluent builders, and before Go 1.26 the compiler rejected it.

Go 1.27: generic methods and friendlier literals

Go 1.27 (August 2026) removes two long-standing restrictions in the language itself.

  • Methods can have their own type parameters. Until now a method could only use the type parameters of its receiver. Now func (b Box[T]) Map[U any](f func(T) U) Box[U] is legal, which makes fluent chains possible. Interface methods still cannot have type parameters, so a generic method cannot be used to satisfy an interface. See generic types and methods.
  • Promoted fields as composite-literal keys. For an embedded struct, Employee{Name: "Mira", Title: "Engineer"} now compiles and fills Person.Name. See embedding.
  • encoding/json/v2 can be imported without an experiment flag in the toolchain used for this course. It is stricter than encoding/json: field names match case-sensitively, nil slices encode as [], and options such as Deterministic give stable output. See JSON.
Go Go 1.27: generic methods, promoted keys and json/v2

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The chain builds a Box[int], doubles it into another Box[int], and then converts it into a Box[string]. Each Map introduced a new type parameter U. The JSON half shows the differences in one glance: v1 matched NAME to the name tag by ignoring case, v2 did not.

Newer versions keep changing, so check the official release notes for anything released after the version this course was verified on (Go 1.27.3). The notes list every change, including platform support and removals that rarely affect application code.

Keeping old programs working: the compatibility promise

With so many changes, why do old programs keep compiling? Go makes two promises.

  1. The Go 1 compatibility promise. Programs written against the Go 1 language and standard library keep compiling and behaving the same with newer releases. New features are added, not substituted.
  2. GODEBUG for the exceptions. When a fix must change observable behavior (the loop variable change, the timer channel change, panic(nil)), Go ships it together with a GODEBUG setting that restores the old behavior. The default for each setting is chosen by the go line in your go.mod: a module that says go 1.20 keeps the Go 1.20 behavior even when built with Go 1.27, until you bump the line. Settings stay available for at least two years (four releases).

You can override a setting for a whole build with the GODEBUG environment variable, for a program with a //go:debug line before the package clause, or for a module with a godebug block in go.mod. The runner on this site compiles a single file without a go.mod, and in that situation the GODEBUG defaults are those of an old Go version, even though the language itself is the newest. That is a perfect way to see the mechanism at work:

Go GODEBUG: the same program with and without a go:debug line

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

With the //go:debug httpmuxgo121=0 line, the pattern GET /items/{id} works and the answer is status 200. Now delete that line and run the program again: the router treats the whole pattern as a literal path, so the request for /items/7 gets 404 page not found. In a real module with go 1.22 or later in go.mod, you get the modern behavior with no extra line. The panic and recover and profiling and debugging lessons show two other settings.

Settings do not live forever. Each one is documented with the release that introduced it and, eventually, the release that removes it. Go 1.27 removed asynctimerchan, the switch for the pre-1.23 timer channels, so a program can no longer ask for the old timers:

Go A removed GODEBUG setting (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The compiler stops with invalid //go:debug: removed GODEBUG "asynctimerchan" set to old value "1" and a link to the documentation. Take that message seriously: a removed setting means the old behavior is gone for good, and the program has to be updated.

Upgrading a project safely

A routine upgrade works well in small steps:

  1. Read the release notes for the new version, especially the "Changes to the language", "Tools" and "Runtime" sections.
  2. Update the toolchain, then run go vet ./... and your tests, with -race if you use goroutines. Behavior changes that GODEBUG protects are still tied to your old go line at this point, so little should break.
  3. Run go fix ./... and review the diff. The modernizers only rewrite code to equivalent, newer forms.
  4. Bump the go line in go.mod. This enables the new language features and flips the GODEBUG defaults to the new behavior. Run the tests again.
  5. Adopt features gradually. There is no need to rewrite working code. Use the new tools in new code and when you touch old code.
Terminal
go version
go fix ./...
go vet ./...
go test -race ./...
go mod edit -go=1.27

go mod tidy -go=1.27 also updates the go line and prunes the dependency graph in one step. Commit the toolchain bump separately from feature work, so a failing test has an obvious cause.

Deprecations and things to stop doing

The newer releases also made some habits obsolete. In new code, prefer:

Old habit Modern replacement
x := x inside loops to capture the variable Nothing: each iteration has its own variable (1.22)
for i := 0; i < n; i++ just to count for i := range n
sort.Slice(s, less) slices.SortFunc(s, cmp) with cmp.Compare
if a < b { return a }; return b min(a, b)
wg.Add(1); go func() { defer wg.Done() ... }() wg.Go(func() { ... }) (1.25)
errors.As(err, &target) with a declared variable errors.AsType[*T](err) (1.26)
x := 5; p := &x to get a pointer to a constant p := new(5) (1.26)
rand.Seed(...) and math/rand globals math/rand/v2
Collecting map keys into a slice by hand slices.Sorted(maps.Keys(m))
Hand-written path checks against .. os.Root (1.24)
for b.N loops in benchmarks for b.Loop() (1.24)

None of the old forms is broken, and they all still compile. But the new forms are shorter and remove a whole category of bugs.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A module's go.mod says go 1.21. It is built with Go 1.27. Which of these still fails to compile?

    Range over an integer is a language feature of Go 1.22, so the go line decides: with go 1.21 the compiler rejects it. min, slices and sync.OnceValue exist in Go 1.21.
  2. 2. What does this print on Go 1.22 or later (module go line 1.22+)? var fs []func(); for i := 0; i < 3; i++ { fs = append(fs, func() { fmt.Print(i) }) }; for _, f := range fs { f() }

    Since Go 1.22 every iteration has its own copy of i, so the closures remember 0, 1 and 2. Before 1.22 they shared one variable and printed 333.
  3. 3. Which release added sync.WaitGroup.Go?

    WaitGroup.Go arrived in Go 1.25, together with testing/synctest becoming stable.
  4. 4. What is a GODEBUG setting for?

    GODEBUG settings keep the compatibility promise: when a change might break existing programs, a setting brings back the old behavior, and the go line in go.mod picks the default.
  5. 5. Which method declaration is legal only in Go 1.27 and later?

    Only the second declares a type parameter of its own on a method. The other three work in earlier releases.

Summary

  • 1.21 added min, max, clear, slices, maps, cmp, log/slog and toolchain management. 1.22 fixed loop variables and added range over integers, new ServeMux patterns and math/rand/v2.
  • 1.23 brought iterators (iter.Seq, range over functions) and reworked timers. 1.24 added generic type aliases, os.Root, string iterators, omitzero and testing.B.Loop.
  • 1.25 added sync.WaitGroup.Go, stable testing/synctest and container-aware GOMAXPROCS. 1.26 added new(expr), errors.AsType, self-referential constraints and go fix modernizers.
  • 1.27 allows methods with their own type parameters and promoted fields as literal keys; encoding/json/v2 can be imported in the toolchain used here.
  • The go line in go.mod selects both the language version and the GODEBUG defaults, so old modules keep their old behavior until you bump it.
  • Upgrade in small steps: read the notes, update the toolchain, run tests and go vet, run go fix, then bump the go line.

Next: Project: Command-Line To-Do Manager