Skip to content

Commit

Permalink
Add an option to consider nil pointers to be equivalent to zero values
Browse files Browse the repository at this point in the history
Similar to NilSlicesAreEmpty and NilStructsAreEmpty, this lets one
consider nil pointers and zero values as equal.
  • Loading branch information
seveas committed Apr 4, 2024
1 parent 95fb3b1 commit 2b8252e
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
9 changes: 9 additions & 0 deletions deep.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ var (

// NilMapsAreEmpty causes a nil map to be equal to an empty map.
NilMapsAreEmpty = false

// NilPointersAreZero causes a nil pointer to be equal to a zero value.
NilPointersAreZero = false
)

var (
Expand Down Expand Up @@ -190,6 +193,12 @@ func (c *cmp) equals(a, b reflect.Value, level int) {
if bElem {
b = b.Elem()
}
if aElem && NilPointersAreZero && !a.IsValid() && b.IsValid() {
a = reflect.Zero(b.Type())
}
if bElem && NilPointersAreZero && !b.IsValid() && a.IsValid() {
b = reflect.Zero(a.Type())
}
c.equals(a, b, level+1)
return
}
Expand Down
24 changes: 24 additions & 0 deletions deep_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1581,3 +1581,27 @@ func TestSliceOrderStruct(t *testing.T) {
t.Fatalf("expected 0 diff, got %d: %s", len(diff), diff)
}
}

func TestNilPointersAreZero(t *testing.T) {
defaultNilPointersAreZero := deep.NilPointersAreZero
deep.NilPointersAreZero = true
defer func() { deep.NilPointersAreZero = defaultNilPointersAreZero }()

type T struct {
S *string
}

a := T{S: nil}
b := T{S: new(string)}

diff := deep.Equal(a, b)
if len(diff) != 0 {
t.Fatalf("expected 0 diff, got %d: %s", len(diff), diff)
}

*b.S = "hello"
diff = deep.Equal(a, b)
if len(diff) != 1 {
t.Fatalf("expected 1 diff, got %d: %s", len(diff), diff)
}
}

0 comments on commit 2b8252e

Please sign in to comment.