Common pitfalls

suggest change

Go is a small language with few surprises, but there are a handful of mistakes that almost every Go programmer makes at some point. Most of them compile without warnings and only show up as wrong results, a leaked resource or a panic in production.

This article lists the most common ones, shows the buggy code next to the fix, and links to articles that cover each topic in more depth.

append can modify a slice you didn't expect

A slice is a view into a backing array. append writes into that array if there is spare capacity, and only allocates a new array when the capacity runs out. Two slices that share a backing array can overwrite each other:

package main

import (
	"fmt"
	"slices"
)

func main() {
	a := make([]int, 3, 10)
	b := append(a, 4)
	c := append(a, 5)
	fmt.Println(a, b, c)

	// fix: limit capacity so append must copy
	a2 := a[:len(a):len(a)]
	d := append(a2, 4)
	e := append(slices.Clip(a), 5)
	fmt.Println(d, e)

	// appending to a sub-slice overwrites the original
	nums := []int{1, 2, 3, 4}
	firstTwo := nums[:2]
	firstTwo = append(firstTwo, 99)
	fmt.Println(nums)
}
[0 0 0] [0 0 0 5] [0 0 0 5]
[0 0 0 4] [0 0 0 5]
[1 2 99 4]

b and c share the same backing array, so the second append overwrote the element written by the first.

Rules of thumb:

See Slices and Duplicate a slice.

range gives you a copy of the element

The value variable in a for range loop is a copy of the element. Modifying it doesn't change the slice:

package main

import "fmt"

type Player struct {
	Name  string
	Score int
}

func main() {
	players := []Player{{"ann", 1}, {"bob", 2}}

	for _, p := range players {
		p.Score += 10 // modifies a copy
	}
	fmt.Println(players)

	for i := range players {
		players[i].Score += 10
	}
	fmt.Println(players)

	byName := map[string]Player{"ann": {"ann", 1}}
	// byName["ann"].Score++ // compile error: cannot assign to struct field in map
	p := byName["ann"]
	p.Score++
	byName["ann"] = p
	fmt.Println(byName)
}
[{ann 1} {bob 2}]
[{ann 11} {bob 12}]
map[ann:{ann 2}]

Index into the slice to modify elements in place. Map values aren't addressable at all: read the value, modify it and store it back, or store pointers (map[string]*Player).

Copying is also a performance concern: ranging over a slice of large structs copies each one. Use the index form or a slice of pointers when structs are big.

Shadowing variables with :=

:= declares new variables if at least one variable on the left is new in the current scope. Inside an if, for or switch block that's a new scope, so := silently creates new variables that hide the outer ones:

package main

import "fmt"

func fromCache() (string, error) { return "cached", nil }

func lookup(useCache bool) (string, error) {
	val := "default"
	if useCache {
		val, err := fromCache() // declares a new val, scoped to the if block
		if err != nil {
			return "", err
		}
		fmt.Println("cache hit:", val)
	}
	return val, nil
}

func main() {
	fmt.Println(lookup(true))
}
cache hit: cached
default <nil>

The fix is to declare err up front and use plain assignment:

	if useCache {
		var err error
		val, err = fromCache()
		if err != nil {
			return "", err
		}
	}

The same mistake is common with err itself: if x, err := f(); ... inside a function that also has an outer err. The shadow analyzer from golang.org/x/tools can find these:

go install golang.org/x/tools/go/analysis/passes/shadow/cmd/shadow@latest
go vet -vettool=$(which shadow) ./...

Writing to a nil map panics

The zero value of a map is nil. Reading from a nil map works and returns zero values, but writing to it panics:

package main

import "fmt"

func main() {
	var counts map[string]int
	fmt.Println(counts["x"], len(counts))

	defer func() { fmt.Println("recovered:", recover()) }()
	counts["x"]++
}
0 0
recovered: assignment to entry in nil map

Initialize maps with make or a literal before writing. This often bites in structs: a struct with a map field has a nil map until you initialize it, so provide a constructor function or initialize lazily:

type Index struct {
	words map[string][]int
}

func (idx *Index) Add(word string, pos int) {
	if idx.words == nil {
		idx.words = make(map[string][]int)
	}
	idx.words[word] = append(idx.words[word], pos)
}

Note that append to a nil slice works fine, which is why idx.words[word] doesn't need initialization. See Zero value of a map.

Map iteration order is random

Go deliberately randomizes the order of iteration over a map. Code that accidentally depends on order will produce different results on each run:

package main

import (
	"fmt"
	"maps"
	"slices"
)

func main() {
	m := map[string]int{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}
	for range 3 {
		for k := range m {
			fmt.Print(k)
		}
		fmt.Println()
	}

	for _, k := range slices.Sorted(maps.Keys(m)) {
		fmt.Print(k, "=", m[k], " ")
	}
	fmt.Println()
}
abcde
eabcd
eabcd
a=1 b=2 c=3 d=4 e=5

The first three lines will differ between runs. When you need stable output (printing, generating files, tests comparing strings), sort the keys first with slices.Sorted(maps.Keys(m)).

A nil pointer in an interface is not nil

An interface value is nil only when both its type and value are nil. Returning a typed nil pointer as an error produces a non-nil error:

package main

import "fmt"

type ValidationError struct{ Field string }

func (e *ValidationError) Error() string { return "invalid " + e.Field }

func validate(name string) error {
	var verr *ValidationError
	if name == "" {
		verr = &ValidationError{Field: "name"}
	}
	return verr // wrong: non-nil interface holding a nil pointer
}

func validateFixed(name string) error {
	if name == "" {
		return &ValidationError{Field: "name"}
	}
	return nil
}

func main() {
	err := validate("ann")
	fmt.Println(err == nil, err)
	fmt.Println(validateFixed("ann") == nil)
}
false <nil>
true

Always return a literal nil for "no error", and declare result types as error, not as a concrete error pointer type. See Equality and comparison for details on how interfaces are compared.

Strings are bytes, not characters

len(s) returns the number of bytes and s[i] returns a byte. For non-ASCII text that is not what you want:

package main

import "fmt"

func main() {
	s := "héllo"
	fmt.Println(len(s), s[1], string(s[1]))

	for i, r := range s {
		fmt.Print(i, ":", string(r), " ")
	}
	fmt.Println()

	runes := []rune(s)
	fmt.Println(len(runes), string(runes[1]))
}
6 195 Ã
0:h 1:é 3:l 4:l 5:o
5 é

é takes 2 bytes in UTF-8. range over a string decodes runes (notice the index jumps from 1 to 3), and converting to []rune gives you indexable code points. Slicing a string like s[:2] can cut a character in half and produce invalid UTF-8. See Characters and runes.

Loop variables and closures before Go 1.22

Before Go 1.22 a for loop had a single variable shared by all iterations. Goroutines or closures that captured it often all saw the last value:

for _, url := range urls {
	go func() {
		fetch(url) // before Go 1.22: all goroutines likely fetch the last url
	}()
}

Since Go 1.22 each iteration gets a fresh variable, and this code is correct. However, the new semantics apply only when the go line in go.mod says go 1.22 or later. If you maintain an old module, either bump the version in go.mod or copy the variable explicitly (url := url). See Closures.

Not waiting for goroutines

When main returns, the program exits, even if goroutines are still running. A related bug is calling wg.Add inside the goroutine, which races with wg.Wait. Since Go 1.25 sync.WaitGroup.Go does Add, Done and starting the goroutine in one call:

package main

import (
	"fmt"
	"sync"
)

func main() {
	var mu sync.Mutex
	var wg sync.WaitGroup
	total := 0
	for i := range 5 {
		wg.Go(func() {
			mu.Lock()
			total += i
			mu.Unlock()
		})
	}
	wg.Wait()
	fmt.Println(total)
}
10

Without the mutex, total += i would be a data race. Run tests with go test -race to catch these. See Wait for goroutines to finish and Detecting races.

Another common leak: a goroutine blocked forever sending on a channel nobody reads anymore, for example after the receiver gave up on a timeout. Use a buffered channel of size 1 for a single result, or select on ctx.Done().

Copying a struct that contains a mutex

sync.Mutex, sync.WaitGroup and similar types must not be copied after first use. Passing a struct by value or using a value receiver copies the mutex, and each copy locks independently:

type Stats struct {
	mu    sync.Mutex
	count int
}

// wrong: value receiver copies the mutex and the counter
func (s Stats) Inc() {
	s.mu.Lock()
	s.count++
	s.mu.Unlock()
}

Use pointer receivers. go vet reports this as passes lock by value. See Mutex gotchas.

Value receivers don't modify the receiver

The same issue applies to any method: a value receiver gets a copy.

package main

import "fmt"

type Counter struct{ n int }

func (c Counter) IncValue()    { c.n++ }
func (c *Counter) IncPointer() { c.n++ }

func main() {
	var c Counter
	c.IncValue()
	c.IncValue()
	fmt.Println(c.n)
	c.IncPointer()
	fmt.Println(c.n)
}
0
1

If a method needs to modify the receiver, use a pointer receiver, and for consistency make all methods of that type pointer receivers. See Pointer vs. value methods.

break inside switch or select

In Go switch cases don't fall through, so you don't need break. But if you write break inside a switch or select that's inside a loop, it exits only the switch, not the loop. Use a label to break out of the loop:

package main

import "fmt"

func main() {
	for i := range 5 {
		switch i {
		case 2:
			break // only exits the switch
		}
		fmt.Print(i, " ")
	}
	fmt.Println()

loop:
	for i := range 5 {
		switch i {
		case 2:
			break loop
		}
		fmt.Print(i, " ")
	}
	fmt.Println()
}
0 1 2 3 4
0 1

This is especially common in for { select { ... } } loops reading from channels. See break and continue.

Integer division, overflow and time.Duration

Integer arithmetic truncates and wraps silently:

package main

import (
	"fmt"
	"time"
)

func main() {
	fmt.Println(7/2, 7.0/2, float64(7)/2, -7/2, -7%3)

	var b int8 = 127
	b++
	fmt.Println(b)

	var u uint = 0
	u--
	fmt.Println(u)

	n := 3
	// time.Sleep(n * time.Second) // compile error: mismatched types int and time.Duration
	d := time.Duration(n) * time.Second
	fmt.Println(d, time.Duration(100))
}
3 3.5 3.5 -3 -1
-128
18446744073709551615
3s 100ns

Things to notice:

defer runs at function exit and evaluates arguments immediately

Two surprises with defer:

package main

import "fmt"

func main() {
	for i := range 3 {
		defer fmt.Println("deferred", i)
	}

	x := 1
	defer fmt.Println("x at defer time:", x)
	defer func() { fmt.Println("x at exit:", x) }()
	x = 2
}
x at exit: 2
x at defer time: 1
deferred 2
deferred 1
deferred 0

Also, os.Exit and log.Fatal exit immediately without running deferred functions. Call them only from main, after cleanup. See Defer pitfalls.

Closed and nil channels

Receiving from a closed channel returns the zero value immediately, sending to a closed channel panics, and both sending to and receiving from a nil channel block forever:

package main

import "fmt"

func main() {
	ch := make(chan int, 1)
	close(ch)

	v, ok := <-ch
	fmt.Println(v, ok)

	defer func() { fmt.Println("recovered:", recover()) }()
	ch <- 1
}
0 false
recovered: send on closed channel

Use the two-value receive v, ok := <-ch or for v := range ch to detect closing. Only the sender should close a channel, and only once. See Closing channels.

JSON silently ignores unexported and unknown fields

encoding/json only sees exported fields, and by default ignores JSON keys that don't match any field. Neither is an error:

package main

import (
	"encoding/json"
	"fmt"
)

type User struct {
	Name     string `json:"name"`
	email    string
	Password string `json:"-"`
}

func main() {
	u := User{Name: "ann", email: "ann@example.com", Password: "secret"}
	data, err := json.Marshal(u)
	fmt.Println(string(data), err)

	var u2 User
	err = json.Unmarshal([]byte(`{"name":"bob","email":"bob@example.com","nmae":"typo"}`), &u2)
	fmt.Printf("%+v %v\n", u2, err)
}
{"name":"ann"} <nil>
{Name:bob email: Password:} <nil>

Capitalize fields you want serialized. To reject unknown keys (and catch typos in config files), use a json.Decoder with DisallowUnknownFields(). See Configuring JSON serialization.

Sub-slices and substrings keep the whole array alive

A small slice or substring of a large one references the same backing memory. As long as the small piece is alive, the garbage collector can't free the large one:

func firstLine(data []byte) []byte {
	i := bytes.IndexByte(data, '\n')
	if i < 0 {
		i = len(data)
	}
	// return data[:i] would keep the whole (possibly huge) data alive
	return bytes.Clone(data[:i])
}

Use bytes.Clone, slices.Clone or strings.Clone when you keep a small piece of a large buffer for a long time. See Memory, escape analysis, and garbage collection.

HTTP client: no timeout and unclosed bodies

http.Get and http.DefaultClient have no timeout, so a stuck server can hang your program forever. And if you don't close the response body, the connection can't be reused and leaks:

client := &http.Client{Timeout: 10 * time.Second}

resp, err := client.Get("https://example.com")
if err != nil {
	return err
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
	return fmt.Errorf("unexpected status: %s", resp.Status)
}
body, err := io.ReadAll(resp.Body)

Also note that a non-2xx status is not an error: err is nil for a 404 or 500, so check resp.StatusCode yourself. See HTTP Client and Timeout requests with a context.

Tools that catch these

Many of these bugs are found automatically:

Summary

Feedback about page:

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



Table Of Contents