go-cmp is a powerful and safer alternative to reflect.DeepEqual for comparing whether two values are semantically equal in Go. It is designed primarily for testing purposes and offers extensive customization through options.
go get github.com/google/go-cmp/cmpgithub.com/google/go-cmp/cmpimport "github.com/google/go-cmp/cmp"For common options:
import "github.com/google/go-cmp/cmp/cmpopts"import (
"testing"
"github.com/google/go-cmp/cmp"
)
func TestStructEquality(t *testing.T) {
type Person struct {
Name string
Age int
}
got := Person{Name: "Alice", Age: 30}
want := Person{Name: "Alice", Age: 30}
if !cmp.Equal(got, want) {
t.Errorf("Person mismatch (-want +got):\n%s", cmp.Diff(want, got))
}
}The go-cmp package provides two core packages:
The package uses an Option-based configuration system that allows customizing comparison behavior through:
Compare values for equality and generate human-readable diffs.
func Equal(x, y interface{}, opts ...Option) boolfunc Diff(x, y interface{}, opts ...Option) stringConfigure comparison behavior with custom equality functions, transformers, and filters.
type Option interface {
// Has unexported methods
}func Comparer(f interface{}) Optionfunc Transformer(name string, f interface{}) Optionfunc Ignore() Optionfunc FilterPath(f func(Path) bool, opt Option) Optionfunc FilterValues(f interface{}, opt Option) OptionNavigate the comparison tree and implement custom reporting.
type Path []PathSteptype PathStep interface {
String() string
Type() reflect.Type
Values() (vx, vy reflect.Value)
}func Reporter(r interface{
PushStep(PathStep)
Report(Result)
PopStep()
}) OptionPre-built options for common comparison scenarios including approximate equality, sorting, and ignoring fields.
func EquateEmpty() cmp.Optionfunc EquateApprox(fraction, margin float64) cmp.Optionfunc IgnoreFields(typ interface{}, names ...string) cmp.Optionfunc IgnoreUnexported(typs ...interface{}) cmp.Optionfunc SortSlices(lessOrCompareFunc interface{}) cmp.Optiontype Options []OptionOptions is a list of Option values that also satisfies the Option interface.
Methods:
String() string - Returns string representationtype Result struct {
// Has unexported fields
}Result represents the comparison result for a single node.
Methods:
Equal() bool - Reports whether the node was determined to be equalByIgnore() bool - Reports whether the node is equal because it was ignoredByFunc() bool - Reports whether a Comparer function determined equalityByMethod() bool - Reports whether the Equal method determined equalityByCycle() bool - Reports whether a reference cycle was detected