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

Support checking if obj is a nil ptr #313

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
7 changes: 7 additions & 0 deletions ptr/ptr.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,10 @@ func Equal[T comparable](a, b *T) bool {
}
return *a == *b
}

// IsNilPtr checks if the provided object is a nil pointer. This is specially useful when dealing
// with interfaces that may hold pointers.
func IsNilPtr(obj any) bool {

Choose a reason for hiding this comment

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

Is this method called from anywhere other than testing?

Copy link
Author

Choose a reason for hiding this comment

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

yes

v := reflect.ValueOf(obj)
return v.Kind() == reflect.Ptr && v.IsNil()
}
20 changes: 20 additions & 0 deletions ptr/ptr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,3 +122,23 @@ func TestEqual(t *testing.T) {
t.Errorf("expected false (val != val)")
}
}

func TestIsNilPtr(t *testing.T) {
var nilIntPointer *int
testCases := []struct {
obj interface{}
expected bool
}{
{(*struct{})(nil), true},
{&struct{}{}, false},
{nilIntPointer, true},
}
for i, tc := range testCases {
name := fmt.Sprintf("case[%d]", i)
t.Run(name, func(t *testing.T) {
if actual := ptr.IsNilPtr(tc.obj); actual != tc.expected {
t.Errorf("%s: expected %t, got %t", name, tc.expected, actual)
}
})
}
}