System Design

G1

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.

Not startedSaved in this browser only.
  1. 1The go line in go.mod picks the language version. A newer toolchain with the old go line keeps the old behaviour.
  2. 2Five rewrites cover most code: min and max, range over int, slices and maps, WaitGroup.Go, and routing patterns.
  3. 3Delete the i := i copies. Each loop iteration has its own variables since 1.22.
  4. 4Run go fix after you raise the go line. It applies these rewrites for you.
G1
    A

    The trap

    one line, two behaviours
    before: language version 1.21go
    //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()
    }
    1. 1This line sets the language version of this file to 1.21. It is the only difference.
    recorded outputstdout
    3 3 3
    after: the go line of this modulego
    package 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()
    }
    1. 1Since 1.22 each iteration has a new i, so each closure holds its own.
    recorded outputstdout
    0 1 2
    what decidesset byscope
    Language version: features and loop rulesgo line in go.modEach module; a //go:build line can change one file.
    Library behaviour defaults, such as timer channelsgo line, GODEBUGThe main module or workspace.
    Which compiler and library runGOTOOLCHAINThe 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.

    B

    Timeline

    the changes that matter most; each version links to its release note
    1.21Aug 2023min, max, clearslog, slices, maps1.22Feb 2024loop variablesrouting patterns1.23Aug 2024range over funciter, timers1.24Feb 2025generic aliasestool, omitzero1.25Aug 2025no language changesynctest, wg.Go1.26Feb 2026new(expr)Green Tea, go fix1.27Aug 2026generic methodsjson/v2, leak profile
    sincewhat changedwhat it replacestaught in
    1.21Built-ins min, max and clear.Hand-written helpers and delete loops.G2 Types and values
    1.21log/slog: structured logs with levels.log.Printf with key=value text.G14 Standard library tour
    1.21Packages slices, maps and cmp.sort.Slice and hand-written loops.G3 Slices, maps and strings inside
    1.21The 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.22Each iteration of a for loop creates new variables.The copy i := i before a closure.G6 Iterators and closures
    1.22for i := range 10: a loop over an integer.Three-part counting loops.G2 Types and values
    1.22ServeMux patterns: methods, {id} wildcards and {$}.Method checks and path parsing in each handler.G16 HTTP
    1.23Range over iterator functions.Callback visitors, and slices built only to loop once.G6 Iterators and closures
    1.23Package iter, with iterators in slices and maps: Sorted, Collect, Keys, Values.Loops that fill a slice, then sort it.G6 Iterators and closures
    1.23Timers: an unstopped timer can be collected, and its channel is unbuffered.Stop-and-drain code around Reset.G11 Primitives
    1.24A type alias can have type parameters.Defined types, which lose the methods.G5 Generics
    1.24encoding/json tag option omitzero, which also honours an IsZero method.Pointers to time.Time, and omitempty on structs.G15 JSON
    1.24tool directives in go.mod, go get -tool, and go tool.A tools.go file with blank imports.G8 Packages and modules
    1.24Maps use Swiss Tables. With other work, CPU overhead falls 2 to 3% on average.No code change.G3 Slices, maps and strings inside
    1.25testing/synctest: a bubble with a fake clock.Real sleeps and injected clocks in tests.G20 Testing
    1.25sync.WaitGroup.Go.wg.Add(1), go func, defer wg.Done().G11 Primitives
    1.25GOMAXPROCS 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.26new takes an expression: new(30), new(f()).A temporary variable, or a ptr[T] helper.G2 Types and values
    1.26go fix is rebuilt around modernizers and //go:fix inline.Manual upgrades to new idioms.G23 Project shape
    1.26The Green Tea collector is the default: an expected 10 to 40% less collection overhead.No code change.G10 The runtime and scheduler
    1.27A method can declare its own type parameters. Interface methods cannot, and a generic method cannot implement one.Package-level generic functions.G5 Generics
    1.27encoding/json/v2 and jsontext. encoding/json now runs on the v2 implementation.Nothing forced: v1 stays supported.G15 JSON
    1.27The 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.

    C

    Language

    from Changes to the language in each release note
    sincewhat changedwhat it replacestaught in
    1.21Built-ins min, max and clear.Hand-written helpers and delete loops.G2 Types and values
    1.21Package 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.21panic(nil) becomes a *runtime.PanicNilError, so recover in a panic never returns nil.A panic that recover could not detect.G7 Errors
    1.21Stronger type inference, also for generic functions passed as arguments.Explicit type arguments.G5 Generics
    1.22Each iteration of a for loop creates new variables.The copy i := i before a closure.G6 Iterators and closures
    1.22for i := range 10: a loop over an integer.Three-part counting loops.G2 Types and values
    1.23Range over iterator functions.Callback visitors, and slices built only to loop once.G6 Iterators and closures
    1.24A type alias can have type parameters.Defined types, which lose the methods.G5 Generics
    1.25No change for programs. The spec removes the term core types.Nothing.G5 Generics
    1.26new takes an expression: new(30), new(f()).A temporary variable, or a ptr[T] helper.G2 Types and values
    1.26A generic type can refer to itself in its type parameter list.Constraints that could not name the type.G5 Generics
    1.27A method can declare its own type parameters. Interface methods cannot, and a generic method cannot implement one.Package-level generic functions.G5 Generics
    1.27A struct literal key can be any valid field selector.Top-level field names only.G2 Types and values
    1.27Function 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.

    D

    Standard library

    the packages a service uses; crypto is left out
    sincewhat changedwhat it replacestaught in
    1.21log/slog: structured logs with levels.log.Printf with key=value text.G14 Standard library tour
    1.21Packages slices, maps and cmp.sort.Slice and hand-written loops.G3 Slices, maps and strings inside
    1.21sync.OnceFunc, OnceValue and OnceValues.A Once, a flag and result fields.G11 Primitives
    1.21context.WithoutCancel, WithDeadlineCause, WithTimeoutCause and AfterFunc.Custom context wrappers.G11 Primitives
    1.22ServeMux patterns: methods, {id} wildcards and {$}.Method checks and path parsing in each handler.G16 HTTP
    1.22math/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.22cmp.Or, database/sql.Null[T], slices.Concat and reflect.TypeFor.Default chains, NullString types, and append chains.G14 Standard library tour
    1.22slices.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.23Package iter, with iterators in slices and maps: Sorted, Collect, Keys, Values.Loops that fill a slice, then sort it.G6 Iterators and closures
    1.23Timers: an unstopped timer can be collected, and its channel is unbuffered.Stop-and-drain code around Reset.G11 Primitives
    1.23Package unique: canonical values and Handle[T].Hand-written interning.G14 Standard library tour
    1.24encoding/json tag option omitzero, which also honours an IsZero method.Pointers to time.Time, and omitempty on structs.G15 JSON
    1.24os.Root: file operations that cannot leave one directory.Path cleaning by hand.G14 Standard library tour
    1.24testing.B.Loop.for range b.N, with its reset timers.G21 Performance
    1.24runtime.AddCleanup, and package weak.runtime.SetFinalizer.G21 Performance
    1.24strings.Lines, SplitSeq and FieldsSeq, with the same set in bytes.strings.Split when the result is read once.G14 Standard library tour
    1.24T.Context and T.Chdir in tests.A context and a cleanup written by hand.G20 Testing
    1.24New sync.Map implementation: writes to disjoint keys contend less.The old sync.Map, with no code change.G11 Primitives
    1.25testing/synctest: a bubble with a fake clock.Real sleeps and injected clocks in tests.G20 Testing
    1.25sync.WaitGroup.Go.wg.Add(1), go func, defer wg.Done().G11 Primitives
    1.25http.CrossOriginProtection: CSRF checks with no tokens or cookies.Token middleware.G16 HTTP
    1.26errors.AsType, a generic errors.As.A target variable for each errors.As.G7 Errors
    1.26slog.NewMultiHandler.A fan-out handler written by hand.G14 Standard library tour
    1.26signal.NotifyContext cancels with a cause that names the signal.A separate channel to learn the signal.G11 Primitives
    1.26ServeMux trailing slash redirects use status 307, not 301.Permanent redirects.G16 HTTP
    1.26httputil.ReverseProxy.Director is deprecated.Move to Rewrite.G16 HTTP
    1.26io.ReadAll is often about 2 times faster, with about half the total memory.The old io.ReadAll, with no code change.G21 Performance
    1.26T.ArtifactDir, and B.Loop no longer blocks inlining in the loop body.Test output in temporary folders.G20 Testing
    1.27encoding/json/v2 and jsontext. encoding/json now runs on the v2 implementation.Nothing forced: v1 stays supported.G15 JSON
    1.27Package uuid generates and parses UUIDs.A third-party UUID module.G14 Standard library tour
    1.27strings.CutLast and bytes.CutLast.strings.LastIndex with slicing.G14 Standard library tour
    1.27synctest.Sleep, and httptest.NewTestServer on a fake network.Sleep then Wait, and a real listener in a bubble.G20 Testing
    1.27HTTP/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.

    E

    Tooling

    the go command, vet, go fix
    sincewhat changedwhat it replacestaught in
    1.21The 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.21The go line of the main module picks GODEBUG defaults.Behaviour that changed with the toolchain.G8 Packages and modules
    1.21A default.pgo file in the main package turns on profile-guided optimization.A manual -pgo flag.G21 Performance
    1.22go work vendor: a vendor folder for a workspace.No vendoring in a workspace.G8 Packages and modules
    1.22go 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.23go mod tidy -diff, and go env -changed.Run tidy, then git diff.G8 Packages and modules
    1.23godebug block in go.mod and go.work.A //go:debug line in a main package.G8 Packages and modules
    1.23go vet stdversion: symbols too new for the go line.A failure on an older toolchain.G8 Packages and modules
    1.23Go telemetry: local counters, and upload only after go telemetry on.Nothing.G23 Project shape
    1.24tool directives in go.mod, go get -tool, and go tool.A tools.go file with blank imports.G8 Packages and modules
    1.24go build -json, and the main module version from the VCS tag in the binary.Parsed text output, and ldflags stamps.G23 Project shape
    1.24GOAUTH authenticates private module fetches.Credentials only in .netrc or Git.G8 Packages and modules
    1.24go vet tests analyzer, and a report on fmt.Printf(s) with a non-constant s.Mistakes found at run time.G20 Testing
    1.25ignore directive in go.mod, and the work package pattern.Underscore prefixes on folders.G8 Packages and modules
    1.25A go line update no longer adds a toolchain line.Unwanted toolchain lines in diffs.G8 Packages and modules
    1.25go vet waitgroup and hostport analyzers.Misplaced Add, and IPv4-only address strings.G13 Races, deadlocks and leaks
    1.25go doc -http.A separate documentation server.G23 Project shape
    1.26go fix is rebuilt around modernizers and //go:fix inline.Manual upgrades to new idioms.G23 Project shape
    1.26go mod init writes the previous release in the go line.New modules that require the newest release.G8 Packages and modules
    1.26pprof web UI opens on the flame graph.The graph view as the default.G21 Performance
    1.27go test runs the stdversion check by default.go vet as a separate step for this check.G20 Testing
    1.27go mod tidy keeps two require blocks: direct and indirect.Scattered require blocks.G8 Packages and modules
    1.27go doc takes pkg@version, and -ex lists examples.A checkout of that version.G23 Project shape
    1.27go vet reports %w with a pointer to an error type.Wrapped errors that errors.Is misses.G7 Errors
    1.27The 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.

    F

    Runtime and compiler

    percentages are the release notes' own estimates
    sincewhat changedwhat it replacestaught in
    1.21Garbage collector tuning: up to 40% less tail latency in some programs.No code change.G21 Performance
    1.22Type metadata sits nearer to heap objects: 1 to 3% less CPU, about 1% less memory.No code change.G21 Performance
    1.22The execution tracer is rebuilt.Traces that were costly to start and stop.G21 Performance
    1.24Maps use Swiss Tables. With other work, CPU overhead falls 2 to 3% on average.No code change.G3 Slices, maps and strings inside
    1.25GOMAXPROCS 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.25runtime/trace.FlightRecorder keeps recent trace data in memory.Full traces, which were too costly to keep on.G21 Performance
    1.25A 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.25The compiler puts slice backing stores on the stack in more cases.No code change.G21 Performance
    1.26The Green Tea collector is the default: an expected 10 to 40% less collection overhead.No code change.G10 The runtime and scheduler
    1.26Baseline cgo call overhead falls about 30%.No code change.G21 Performance
    1.26The heap base address is random at start on 64-bit platforms.A fixed base.G22 Reflection and unsafe
    1.27The goroutineleak profile is generally available.Reading goroutine dumps by eye.G13 Races, deadlocks and leaks
    1.27Size-specialized allocation: up to 30% cheaper for some objects under 80 bytes, about 1% in real programs.No code change.G21 Performance
    1.27Tracebacks show goroutine labels when the go line is 1.27 or later.Finding the request by hand.G10 The runtime and scheduler
    1.27The 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.

    G

    min, max, clear

    since 1.21
    before: up to 1.20go
    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)
    }
    1. 1The NaN key is not equal to itself, so delete finds nothing. One entry stays.
    recorded outputstdout
    3
    left in map: 1
    [0 0 0]
    after: since 1.21go
    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)
    }
    1. 1Built-ins take any number of arguments of an ordered type.
    2. 2Removes every entry, also a NaN key.
    3. 3Sets every element to zero. The length stays.
    recorded outputstdout
    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.

    H

    Range over an integer

    since 1.22
    before: up to 1.21go
    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()
    }
    recorded outputstdout
    0 1 2 
    retry retry
    after: since 1.22go
    package main
    
    import "fmt"
    
    func main() {
      for i := range 3 {
        fmt.Print(i, " ")
      }
      fmt.Println()
    
      for range 21 {
        fmt.Print("retry ")
      }
      fmt.Println()
    }
    1. 1Drop the variable when the loop needs only a count.
    recorded outputstdout
    0 1 2 
    retry retry

    for range n says that I want n rounds and no index.

    I

    Range over a function

    since 1.23
    before: up to 1.22go
    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()
    }
    1. 1Stop means a return value. The caller cannot use break or return here.
    recorded outputstdout
    1 2
    after: since 1.23go
    package 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()
    }
    1. 1A named form of func(yield func(int) bool).
    2. 2yield returns false, and the iterator stops.
    recorded outputstdout
    1 2

    An iterator is a function that takes yield. The caller writes a normal loop, and a break reaches the iterator as a false result.

    J

    Routing patterns

    since 1.22
    before: up to 1.21go
    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)
      }
    }
    1. 1The prefix pattern also accepts /items/42/extra, and the id is wrong.
    recorded outputstdout
    GET /items/42 200 item 42
    POST /items/42 405 
    GET /items/42/extra 200 item 42/extra
    after: since 1.22go
    package 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)
      }
    }
    1. 1The method and one path segment are in the pattern. GET also registers HEAD.
    2. 2Reads the wildcard.
    recorded outputstdout
    GET /items/42 200 item 42
    POST /items/42 405 Method Not Allowed
    GET /items/42/extra 404 404 page not found

    I 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.

    K

    Structured logs

    since 1.21
    before: up to 1.20go
    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)
    }
    1. 1Every call repeats the fields, and a log tool must parse the text.
    recorded outputstdout
    order=1042 user=u7 msg="paid in full"
    order=1042 user=u7 retries=2
    after: since 1.21go
    package 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")
    }
    1. 1Each line from req carries these fields.
    2. 2The default level is Info, so this line prints nothing.
    3. 3Only here so that the recorded output has no clock.
    recorded outputstdout
    {"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.

    L

    slices and maps

    slices, maps since 1.21; iterators since 1.23
    before: up to 1.20go
    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))
    }
    recorded outputstdout
    [apple fig pear]
    true
    3
    after: since 1.23go
    package 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))
    }
    1. 1maps.Keys returns an iterator. slices.Sorted collects it and sorts.
    2. 2A shallow copy.
    recorded outputstdout
    [apple fig pear]
    true
    3

    slices.Sorted(maps.Keys(m)) is one line, and it replaces a loop, an append and a sort.

    M

    Generic type aliases

    since 1.24
    before: up to 1.23go
    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))
    }
    1. 1A defined type is a new type. It has no methods from Tree.
    recorded outputstdout
    main.ByName[int] 1
    after: since 1.24go
    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 }
    
    // 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))
    }
    1. 1The = makes an alias, and %T prints the real type.
    recorded outputstdout
    main.Tree[string,int] 1

    A generic alias keeps the type and its methods, so I can move a type between packages one step at a time.

    N

    omitzero

    since 1.24
    before: up to 1.23go
    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))
    }
    1. 1omitempty has no effect on a struct.
    2. 2The old fix: a pointer, only to get nil.
    recorded outputstdout
    {"name":"ship","due":"0001-01-01T00:00:00Z"}
    after: since 1.24go
    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))
    }
    1. 1Uses the IsZero method when the type has one, as time.Time does.
    recorded outputstdout
    {"name":"ship"}

    omitempty never removes a struct, so a zero time.Time prints as year 1. omitzero removes it.

    O

    Test time with synctest

    since 1.25
    before: up to 1.24go
    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)
    }
    1. 1A real wait. Too short is flaky, and too long is slow.
    recorded outputstdout
    expired
    real wait >= ttl: true
    after: since 1.25go
    package 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,
      )
    }
    1. 1Starts a bubble with a fake clock.
    2. 2Returns when every other goroutine in the bubble is blocked or finished.
    3. 3Only here so that a plain program can run a test. Normal code uses go test.
    recorded outputstdout
    expired
    fake time: 1h0m0s
    real wait < 1s: true
    PASS

    In a synctest bubble, an hour passes at once, because the clock jumps when every goroutine in the bubble blocks.

    P

    WaitGroup.Go

    since 1.25
    before: up to 1.24go
    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())
    }
    1. 1Must run before the go statement. go vet reports a misplaced Add since 1.25.
    recorded outputstdout
    6
    after: since 1.25go
    package 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())
    }
    1. 1Adds 1, starts the goroutine, and calls Done when the function returns.
    recorded outputstdout
    6

    wg.Go does the Add and the Done, so I cannot put the Add in the wrong place.

    Q

    new with an expression

    since 1.26
    before: up to 1.25go
    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)
    }
    1. 1Most projects carried this helper.
    recorded outputstdout
    {"name":"Ana","age":36}
    {"name":"Bo","age":25}
    {"name":"Cy"}
    after: since 1.26go
    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)
    }
    1. 1A new variable holds the result of the expression.
    recorded outputstdout
    {"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.

    R

    Generic methods

    since 1.27
    before: up to 1.26go
    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)
    }
    1. 1The function wraps the chain, so it reads inside out.
    recorded outputstdout
    ["2" "4"]
    after: since 1.27go
    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)
    }
    1. 1U belongs to this method. T comes from the receiver.
    2. 2U is inferred from the argument.
    recorded outputstdout
    ["2" "4"]

    A method can now declare a type parameter, so calls chain left to right. Interfaces still cannot have generic methods.

    S

    The goroutine leak profile

    experiment in 1.26, generally available in 1.27
    before: up to 1.26go
    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)
    }
    1. 1A count of all goroutines. It cannot tell a parked worker from a leak.
    recorded outputstdout
    goroutines: 5
    after: since 1.27go
    package 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)
    }
    1. 1Also served at /debug/pprof/goroutineleak.
    2. 2The collector finds blocked goroutines whose channel no running goroutine can reach.
    recorded outputstdout
    leaked: 2
    blocked in: main.first.func1

    The 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.

    T

    In the round

    45 minutes of build, 45 minutes of talk
    whenthe momentwhat to do or saystatus
    buildRoutes for a small API.Use ServeMux patterns with a method and a wildcard.Approved
    buildStable output from a map.Use slices.Sorted(maps.Keys(m)).Approved
    buildFan out in a test.Use wg.Go. Drop i := i inside the loop.Approved
    buildAn optional field in a response.Use new(expr) for a pointer, and omitzero for a time.Approved
    buildA 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.

    U

    Drill

    each answer is the output of a real run

    0 of 12 known

    1. 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)
      }
    2. 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))
      }
    3. 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")
      }
    4. 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")
      }
    5. 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
        }
      }
    6. 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()
        }
      }
    7. 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")
      }
    8. 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)
      }
    9. Predict the output.

      package main
      
      import "fmt"
      
      func main() {
        defer func() {
          r := recover()
          fmt.Printf("%T\n", r)
          fmt.Println(r != nil)
        }()
        panic(nil)
      }
    10. 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)
      }
    11. 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))
      }
    12. 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)
      }