Test Failed: How to Print Exact Diffs for Complex Go Structs with go-cmpArticle · digest for October 26
Terminal Go test debugging interface with pinpoint google/go-cmp diff highlighting on a graphite screen.
Article3 sections≈ 4 min

Test Failed: How to Print Exact Diffs for Complex Go Structs with go-cmp

Picture a familiar moment: you run the test suite in a Go project, and one test fails with a terse expected true, got false. You open the test file and see the classic reflect.DeepEqual(want, got). The input is a nested API response struct with thirty fields, embedded slices, timestamps, and metadata. Which field actually mismatched? No clue.

So you start adding fmt.Printf("%+v\n") debug prints, marshaling objects to pretty-printed JSON, and eyeballing two wall-of-text dumps side by side. What should have been a two-second fix turns into fifteen minutes of squinting for a typo in a single boolean flag.

That pain has haunted Go's standard library for years: reflect.DeepEqual gives you a binary yes/no and zero context. Google's engineers built the official go-cmp library (currently at v0.7.0) specifically for tests, turning failure output into a surgical comparison.

Anatomy of cmp.Diff: Reading -want and +got Markers

The workhorse of the package is cmp.Diff(want, got). When two values match, it returns an empty string. When anything differs—even deep inside nested structs—it returns a compact, human-readable report highlighting only the mismatched fields.

Add the package to your project with the standard command:

go get -u github.com/google/go-cmp/cmp@v0.7.0

The diff output uses an intuitive notation:

  • Lines starting with minus (-) show the expected value (want);
  • Lines starting with plus (+) show what your code actually returned (got).

Look how clean and expressive your test assertions become:

package user_test

import (
    "testing"
    "github.com/google/go-cmp/cmp"
    "github.com/google/go-cmp/cmp/cmpopts"
)

type UserProfile struct {
    ID       int64
    Username string
    Roles    []string
    authHash string // private unexported field
}

func TestUserProfile(t *testing.T) {
    want := UserProfile{
        ID:       42,
        Username: "alex",
        Roles:    nil, // nil slice
    }
    got := UserProfile{
        ID:       42,
        Username: "alex",
        Roles:    []string{}, // empty zero-length slice
    }

    // Configure comparison rules: ignore private fields and equate empty collections
    diff := cmp.Diff(want, got,
        cmpopts.IgnoreUnexported(UserProfile{}),
        cmpopts.EquateEmpty(),
    )

    if diff != "" {
        t.Errorf("UserProfile mismatch (-want +got):\n%s", diff)
    }
}

Remove those options, and the test immediately pinpoints the exact nested difference without cluttering the output with matching fields. It fits right into TDD practices and reliable Go testing: a failing test should tell you why it failed at a glance.

The Empty-Slice Trap and Unexported Fields

Most developers trying go-cmp for the first time run into two deliberate design quirks:

  1. Strict distinction between nil and an empty slice: in Go, var s []string = nil and s := []string{} are semantically different even though both have length zero. By default, go-cmp treats them as unequal! If your business logic doesn't care about the difference, pass cmpopts.EquateEmpty(). Just be careful: if your JSON serializer is supposed to emit null rather than [], blindly equating them will hide a contract bug.
  2. Panicking on unexported fields: if a struct contains lowercase private fields (like authHash), go-cmp intentionally panics (panic: cannot handle unexported field) to protect type encapsulation. You have to state your intent explicitly: either skip them with cmpopts.IgnoreUnexported(Type{}) or inspect them with cmp.AllowUnexported(Type{}).

Custom Comparers and Where Not to Use It

Another superpower of cmp.Diff is defining custom comparison rules via cmp.Comparer. A classic example is comparing time.Time values, where monotonic clock readings or nanosecond drift can trigger flaky failures:

// Comparer that truncates timestamps to seconds before comparing
var timeComparer = cmp.Comparer(func(x, y time.Time) bool {
    return x.Truncate(time.Second).Equal(y.Truncate(time.Second))
})

One important boundary to keep in mind: go-cmp is designed strictly for tests. Because it relies heavily on reflection, it isn't tuned for high-throughput production paths and can be slow on slices with tens of thousands of elements. Keep it out of production business logic.

For everyday unit and integration tests, though, go-cmp saves a ton of time and frustration by making test failures self-explanatory on the first read.

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 2