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 all commits
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
16 changes: 12 additions & 4 deletions 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.Map, reflect.Ptr, reflect.Slice:
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 All @@ -358,14 +367,13 @@ func IsZero(data interface{}) bool {
return v.Uint() == 0
case reflect.Float32, reflect.Float64:
return v.Float() == 0
case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
return v.IsNil()
case reflect.Struct, reflect.Array:
return reflect.DeepEqual(data, reflect.Zero(v.Type()).Interface())
case reflect.Invalid:
return true
default:
return false
}
return false
}

// AddInitialisms add additional initialisms
Expand Down
11 changes: 11 additions & 0 deletions util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,14 @@ type ZeroesWithTime struct {
Time time.Time
}

type dummyZeroable struct {
zero bool
}

func (d dummyZeroable) IsZero() bool {
return d.zero
}

func TestIsZero(t *testing.T) {
var strs [5]string
var strss []string
Expand Down Expand Up @@ -384,6 +392,9 @@ func TestIsZero(t *testing.T) {
{[...]string{"hello"}, false},
{[]string(nil), true},
{[]string{"a"}, false},
{&dummyZeroable{true}, true},
{&dummyZeroable{false}, false},
{(*dummyZeroable)(nil), true},
}

for _, it := range data {
Expand Down