go fix and modernizers

suggest change

Go keeps adding small conveniences: any (1.18), min and max (1.21), the slices and maps packages (1.21), range over an integer (1.22), strings.SplitSeq (1.24), sync.WaitGroup.Go (1.25), errors.AsType (1.26). Old code still compiles, so nothing forces you to switch. go fix does the switching for you.

Before Go 1.26, go fix only knew a few ancient rewrites for pre-Go 1 APIs and almost nobody ran it. Go 1.26 rebuilt it on the same analysis framework that go vet uses. It now runs a set of modernizers: analyzers that find old idioms and rewrite them to the modern equivalent without changing what the program does. Go 1.27 added more of them.

This article covers:

All output below is from Go 1.27.

Running go fix

go fix takes package patterns, like go build and go vet:

go fix ./...           # rewrite files in place
go fix -diff ./...     # only print a unified diff

It changes your files in place, so commit (or stash) first. Then you can review the change with git diff and throw it away if you don't like it.

Here's a file written in an older style. It compiles, and go vet has nothing to say about it:

package demo

import (
	"encoding/json"
	"fmt"
	"sort"
	"strings"
	"sync"
)

func Describe(v interface{}) string {
	return fmt.Sprintf("%v", v)
}

func Squares(n int) []int {
	var res []int
	for i := 0; i < n; i++ {
		res = append(res, i*i)
	}
	return res
}

func HasAdmin(roles []string) bool {
	for _, r := range roles {
		if r == "admin" {
			return true
		}
	}
	return false
}

func ParseKV(s string) (string, string, bool) {
	i := strings.Index(s, "=")
	if i < 0 {
		return "", "", false
	}
	return s[:i], s[i+1:], true
}

func StripV(tag string) string {
	if strings.HasPrefix(tag, "v") {
		return strings.TrimPrefix(tag, "v")
	}
	return tag
}

func SortedNames(names []string) []string {
	sort.Slice(names, func(i, j int) bool { return names[i] < names[j] })
	return names
}

func CountWords(text string) int {
	n := 0
	for _, w := range strings.Split(text, " ") {
		if w != "" {
			n++
		}
	}
	return n
}

func ProcessAll(items []string, f func(string)) {
	var wg sync.WaitGroup
	for _, it := range items {
		it := it
		wg.Add(1)
		go func() {
			defer wg.Done()
			f(it)
		}()
	}
	wg.Wait()
}

type Address struct {
	City string `json:"city"`
}

type User struct {
	Name    string  `json:"name"`
	Address Address `json:"address,omitempty"`
}

func Encode(u User) ([]byte, error) {
	return json.Marshal(u)
}

The module's go.mod says go 1.27. Preview what go fix would do:

go fix -diff ./...
# example.com/demo
fix.exe: omitzero: ignoring alternative fix "Replace omitempty with omitzero (behavior change)"
--- ...\demo\old.go (old)
+++ ...\demo\old.go (new)
@@ -3,12 +3,12 @@
 import (
 	"encoding/json"
 	"fmt"
-	"sort"
+	"slices"
 	"strings"
 	"sync"
 )
 
-func Describe(v interface{}) string {
+func Describe(v any) string {
 	return fmt.Sprintf("%v", v)
 }
 
@@ -31,44 +27,39 @@
 
 func Squares(n int) []int {
 	var res []int
-	for i := 0; i < n; i++ {
+	for i := range n {
 		res = append(res, i*i)
 	}
 	return res
 }
 
 func HasAdmin(roles []string) bool {
-	for _, r := range roles {
-		if r == "admin" {
-			return true
-		}
-	}
-	return false
+	return slices.Contains(roles, "admin")
 }
 
 func ParseKV(s string) (string, string, bool) {
-	i := strings.Index(s, "=")
-	if i < 0 {
+	before, after, ok := strings.Cut(s, "=")
+	if !ok {
 		return "", "", false
 	}
-	return s[:i], s[i+1:], true
+	return before, after, true
 }
 
 func StripV(tag string) string {
-	if strings.HasPrefix(tag, "v") {
-		return strings.TrimPrefix(tag, "v")
+	if after, ok := strings.CutPrefix(tag, "v"); ok {
+		return after
 	}
 	return tag
 }
 
 func SortedNames(names []string) []string {
-	sort.Slice(names, func(i, j int) bool { return names[i] < names[j] })
+	slices.Sort(names)
 	return names
 }
 
 func CountWords(text string) int {
 	n := 0
-	for _, w := range strings.Split(text, " ") {
+	for w := range strings.SplitSeq(text, " ") {
 		if w != "" {
 			n++
 		}
@@ -79,12 +46,9 @@
 func ProcessAll(items []string, f func(string)) {
 	var wg sync.WaitGroup
 	for _, it := range items {
-		it := it
-		wg.Add(1)
-		go func() {
-			defer wg.Done()
+		wg.Go(func() {
 			f(it)
-		}()
+		})
 	}
 	wg.Wait()
 }
@@ -95,7 +58,7 @@
 
 type User struct {
 	Name    string  `json:"name"`
-	Address Address `json:"address,omitempty"`
+	Address Address `json:"address"`
 }
 
 func Encode(u User) ([]byte, error) {

(I shortened the long file paths.) Every function got simpler, and none of them behaves differently:

The last one deserves a closer look. omitempty doesn't omit struct values, so "address" was always encoded. The omitzero modernizer offers two fixes: drop the useless omitempty (no change in output), or replace it with omitzero (Go 1.24), which really omits a zero struct. The second one changes the JSON you produce, so go fix refuses to pick it and says so on stderr. If omitting the field is what you meant, change the tag to omitzero by hand. Zero values and absence explains the difference.

-diff exits with status 1 when the diff isn't empty and 0 when there is nothing to fix:

go fix ./...
go fix -diff ./...
echo "exit=$?"
# example.com/demo
fix.exe: omitzero: ignoring alternative fix "Replace omitempty with omitzero (behavior change)"
exit=0

That makes go fix -diff ./... usable as a CI check that fails when someone adds old-style code.

More modernizers

A second file, together with a test:

package t2

import (
	"errors"
	"io/fs"
)

func Larger(a, b int) int {
	var m int
	if a > b {
		m = a
	} else {
		m = b
	}
	return m
}

func Merge(dst, src map[string]int) {
	for k, v := range src {
		dst[k] = v
	}
}

func Join(words []string) string {
	s := ""
	for _, w := range words {
		s += w + ","
	}
	return s
}

func PathOf(err error) string {
	var pe *fs.PathError
	if errors.As(err, &pe) {
		return pe.Path
	}
	return ""
}
package t2

import (
	"context"
	"testing"
)

func TestSomething(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	_ = ctx
}

go fix -diff ./... prints:

--- ...\t2\a.go (old)
+++ ...\t2\a.go (new)
@@ -3,35 +3,30 @@
 import (
 	"errors"
 	"io/fs"
+	"maps"
+	"strings"
 )
 
 func Larger(a, b int) int {
 	var m int
-	if a > b {
-		m = a
-	} else {
-		m = b
-	}
+	m = max(a, b)
 	return m
 }
 
 func Merge(dst, src map[string]int) {
-	for k, v := range src {
-		dst[k] = v
-	}
+	maps.Copy(dst, src)
 }
 
 func Join(words []string) string {
-	s := ""
+	var s strings.Builder
 	for _, w := range words {
-		s += w + ","
+		s.WriteString(w + ",")
 	}
-	return s
+	return s.String()
 }
 
 func PathOf(err error) string {
-	var pe *fs.PathError
-	if errors.As(err, &pe) {
+	if pe, ok := errors.AsType[*fs.PathError](err); ok {
 		return pe.Path
 	}
 	return ""
--- ...\t2\a_test.go (old)
+++ ...\t2\a_test.go (new)
@@ -1,12 +1,10 @@
 package t2
 
 import (
-	"context"
 	"testing"
 )
 
 func TestSomething(t *testing.T) {
-	ctx, cancel := context.WithCancel(context.Background())
-	defer cancel()
+	ctx := t.Context()
 	_ = ctx
 }

The fixes add the imports they need (maps, strings) and remove the ones that are no longer used (context).

Test files are fixed too. t.Context() (Go 1.24) returns a context that is canceled just before the test's cleanup functions run, so the WithCancel/defer cancel() pair isn't needed.

Notice what the modernizers leave alone:

Modernizers are conservative. They skip code where the rewrite could change behavior, even in an unlikely corner case, and they skip generated files (files with a // Code generated ... DO NOT EDIT. comment) entirely.

The go line in go.mod decides what is allowed

A modernizer only uses a feature if the code is allowed to use it. The limit is the go line in go.mod (or a //go:build go1.N constraint on a file). Code in a module that says go 1.21 can't use range n (1.22), strings.SplitSeq (1.24) or wg.Go (1.25), and go fix knows that.

Here's the first file again, in a copy of the module whose go.mod says go 1.21. Showing only the changed lines:

go fix -diff ./... | grep '^[-+]'
-	"sort"
+	"slices"
-func Describe(v interface{}) string {
+func Describe(v any) string {
-	for _, r := range roles {
-		if r == "admin" {
-			return true
-		}
-	}
-	return false
+	return slices.Contains(roles, "admin")
-	i := strings.Index(s, "=")
-	if i < 0 {
+	before, after, ok := strings.Cut(s, "=")
+	if !ok {
-	return s[:i], s[i+1:], true
+	return before, after, true
-	if strings.HasPrefix(tag, "v") {
-		return strings.TrimPrefix(tag, "v")
+	if after, ok := strings.CutPrefix(tag, "v"); ok {
+		return after
-	sort.Slice(names, func(i, j int) bool { return names[i] < names[j] })
+	slices.Sort(names)

any, slices and strings.Cut are older than 1.21, so they are applied. The range n loop, SplitSeq, wg.Go, the it := it removal and the omitzero fix are not.

This gives a natural upgrade routine. When you raise the go line, run go fix ./... and the code catches up with the newly allowed features.

Run it a second time, too. One fix can make another one possible, and a second run picks those up. Repeat until go fix -diff exits with 0.

Listing the fixers

go fix runs the fix tool, cmd/fix. To see what it knows:

go tool fix help
...
Registered analyzers:

    any          replace interface{} with any
    atomictypes  replace basic types in sync/atomic calls with atomic types
    buildtag     check //go:build and // +build directives
    embedlit     simplify references to embedded fields in composite literals
    errorsastype replace errors.As with errors.AsType[T]
    forvar       remove redundant re-declaration of loop variables
    hostport     check format of addresses passed to net.Dial
    inline       apply fixes based on 'go:fix inline' comment directives
    mapsloop     replace explicit loops over maps with calls to maps package
    minmax       replace if/else statements with calls to min or max
    newexpr      simplify code by using go1.26's new(expr)
    omitzero     suggest replacing omitempty with omitzero for struct fields
    plusbuild    remove obsolete //+build comments
    rangeint     replace 3-clause for loops with for-range over integers
    reflecttypefor replace reflect.TypeOf(x) with TypeFor[T]()
    slicesbackward replace backward loops over slices with slices.Backward
    slicescontains replace loops with slices.Contains or slices.ContainsFunc
    slicessort   replace sort.Slice with slices.Sort for basic types
    stditerators use iterators instead of Len/At-style APIs
    stringsbuilder replace += with strings.Builder
    stringscut   replace strings.Index etc. with strings.Cut
    stringscutprefix replace HasPrefix/TrimPrefix with CutPrefix
    stringsseq   replace ranging over Split/Fields with SplitSeq/FieldsSeq
    testingcontext replace context.WithCancel with t.Context in tests
    unsafefuncs  replace unsafe pointer arithmetic with function calls
    waitgroupgo  replace wg.Add(1)/go/wg.Done() with wg.Go

By default all analyzers are run.
To select specific analyzers, use the -NAME flag for each one,
 or -NAME=false to run all analyzers not explicitly disabled.
...

Each fixer has its own documentation, including what it deliberately doesn't touch:

go tool fix help minmax
minmax: replace if/else statements with calls to min or max

The minmax analyzer simplifies conditional assignments by suggesting the use
of the built-in `min` and `max` functions, introduced in Go 1.21. For example,

	if a < b { x = a } else { x = b }

is replaced by

	x = min(a, b).

This analyzer avoids making suggestions for floating-point types,
as the behavior of `min` and `max` with NaN values can differ from
the original if/else statement.

A few fixers aren't modernizers. buildtag and hostport are go vet checks that happen to come with a suggested fix, and plusbuild deletes // +build lines that have been redundant since //go:build arrived in Go 1.17.

There is no fixer that converts for i := 0; i < b.N; i++ benchmarks to b.Loop() (Go 1.24), and rangeint leaves b.N loops alone. That conversion changes what the benchmark measures, so you have to do it by hand.

Selecting fixers

Fixer flags are passed through go fix. Naming a fixer runs only the named ones:

go fix -diff -rangeint -any ./... | grep '^[-+]'
--- ...\demo\old.go (old)
+++ ...\demo\old.go (new)
-func Describe(v interface{}) string {
+func Describe(v any) string {
-	for i := 0; i < n; i++ {
+	for i := range n {

-NAME=false turns off one fixer and keeps all the others:

go fix -omitzero=false -waitgroupgo=false ./...

On a big code base, applying one fixer per commit makes the changes much easier to review: one commit that only replaces interface{} with any, another that only converts loops, and so on.

Migrating your own API with //go:fix inline

The inline fixer is different from the others. It doesn't know any idioms. It acts on a directive you put in your own code, so that users of your package can migrate off a deprecated function, constant or type alias automatically.

Here is a package where Square, DefPrec and Number are old names we'd like to retire:

package mathx

import "math"

// Pow returns x raised to the power n.
func Pow(x float64, n int) float64 {
	return math.Pow(x, float64(n))
}

// Square returns x*x.
//
// Deprecated: use Pow(x, 2).
//
//go:fix inline
func Square(x float64) float64 { return Pow(x, 2) }

// Deprecated: use DefaultPrecision.
//
//go:fix inline
const DefPrec = DefaultPrecision

const DefaultPrecision = 6

// Number is the old name for Value.
//
// Deprecated: use Value.
//
//go:fix inline
type Number = Value

type Value float64

The trick is to write the old API in terms of the new one, then mark it with //go:fix inline. The fixer replaces each call with the function's body, with the arguments substituted.

The directive works on:

A program that uses the old names:

package main

import (
	"fmt"

	"example.com/inl/mathx"
)

func side() float64 {
	fmt.Println("side effect")
	return 3
}

func main() {
	var n mathx.Number = 4
	fmt.Println(mathx.Square(1.5), n, mathx.DefPrec)
	fmt.Println(mathx.Square(side()))
}
2.25 4 6
side effect
9

go fix -diff ./...:

--- ...\inl\cmd\app\main.go (old)
+++ ...\inl\cmd\app\main.go (new)
@@ -12,7 +12,7 @@
 }
 
 func main() {
-	var n mathx.Number = 4
-	fmt.Println(mathx.Square(1.5), n, mathx.DefPrec)
-	fmt.Println(mathx.Square(side()))
+	var n mathx.Value = 4
+	fmt.Println(mathx.Pow(1.5, 2), n, mathx.DefaultPrecision)
+	fmt.Println(mathx.Pow(side(), 2))
 }

The inliner makes sure it doesn't change behavior. Square(side()) became Pow(side(), 2) because the parameter x is used exactly once, so side() still runs exactly once. If the parameter were used several times, the call can't be inlined that simply:

// Deprecated: use Mul3.
//
//go:fix inline
func Cube(x float64) float64 { return Mul3(x, x, x) }

func Mul3(a, b, c float64) float64 { return a * b * c }
func cubes() (float64, float64) {
	return mathx.Cube(2), mathx.Cube(side())
}
@@ -3,5 +3,5 @@
 import "example.com/inl/mathx"
 
 func cubes() (float64, float64) {
-	return mathx.Cube(2), mathx.Cube(side())
+	return mathx.Mul3(2, 2, 2), mathx.Cube(side())
 }

The constant 2 is safely duplicated. Mul3(side(), side(), side()) would call side three times, so that call is left alone. Fixing it would need a separate var x = side() statement, and go fix doesn't add those by default because the result often reads worse than the original.

The workflow for library authors

  1. Add the new API.
  2. Rewrite the old function, constant or type as a thin wrapper around the new one.
  3. Mark it // Deprecated: (so editors and staticcheck warn about it) and //go:fix inline.
  4. Release. Users who upgrade run go fix ./... and their calls are rewritten.
  5. Remove the old API in a later major version.

The same trick works for moving to a new major version of a module: in v1, implement each function by calling its v2 counterpart and mark it //go:fix inline. The fixer rewrites callers to import v2 directly.

A call from TestF, the dedicated test of a deprecated F, is never inlined: that test is supposed to keep testing F itself.

go fix, go vet and gofmt

Tool What it does Changes files?
gofmt / go fmt layout: whitespace, indentation, import grouping yes
go vet reports likely bugs no
go fix rewrites old idioms to modern ones, applies //go:fix inline yes (-diff to preview)

See go fmt for the formatter and go vet for the bug checker. For your own large-scale rewrites that go beyond what the fixers know, see Code generation with go/ast, and -fixtool=prog lets go fix run your own analysis tool instead of cmd/fix.

A sensible routine:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents