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

check for nil pointers before calling IsZero. #67

Merged
merged 3 commits into from
Mar 28, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 10 additions & 1 deletion util.go
Original file line number Diff line number Diff line change
Expand Up @@ -341,12 +341,21 @@ type zeroable interface {
// IsZero returns true when the value passed into the function is a zero value.
// This allows for safer checking of interface values.
func IsZero(data interface{}) bool {
v := reflect.ValueOf(data)
// check for nil data
switch v.Kind() {
case reflect.Interface, reflect.Ptr:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about also checking for reflect.Slice and removing the (now duplicated) check below then?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

changed, thanks!

if v.IsNil() {
return true
}
}

// check for things that have an IsZero method instead
if vv, ok := data.(zeroable); ok {
return vv.IsZero()
}

// continue with slightly more complex reflection
v := reflect.ValueOf(data)
switch v.Kind() {
case reflect.String:
return v.Len() == 0
Expand Down
18 changes: 18 additions & 0 deletions util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -490,3 +490,21 @@ func TestToGoNameUnicode(t *testing.T) {
assert.Equal(t, sample.out, ToGoName(sample.str))
}
}

type dummyZeroable struct {
zero bool
}

func (d dummyZeroable) IsZero() bool {
return d.zero
}
func TestZeroableNilIsZero(t *testing.T) {
var d *dummyZeroable

assert.True(t, IsZero(d))
}

func TestZeroableInterfaceIsRespected(t *testing.T) {
assert.False(t, IsZero(dummyZeroable{false}))
assert.True(t, IsZero(dummyZeroable{true}))
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can't we integrate this is the existing TestIsZero test?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, we can. Moved, thanks!