Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add an option to consider nil pointers to be equivalent to zero values #61

Merged
merged 2 commits into from
Jun 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
}
Loading