diff --git a/gptr/gptr.go b/gptr/gptr.go index 0d20545..2de44e5 100644 --- a/gptr/gptr.go +++ b/gptr/gptr.go @@ -139,6 +139,11 @@ func IsNotNil[T any](p *T) bool { return p != nil } +// IsNilOrZero returns whether the given pointer p is nil or the value it points to is zero. +func IsNilOrZero[T comparable](p *T) bool { + return p == nil || gvalue.IsZero(*p) +} + // Clone returns a shallow copy of the slice. // If the given pointer is nil, nil is returned. // diff --git a/gptr/gptr_test.go b/gptr/gptr_test.go index 6199d9d..f26fc9b 100644 --- a/gptr/gptr_test.go +++ b/gptr/gptr_test.go @@ -81,6 +81,14 @@ func TestIsNil(t *testing.T) { assert.True(t, IsNil[int](nil)) } +func TestIsNilOrZero(t *testing.T) { + assert.False(t, IsNilOrZero(Of(1))) + assert.False(t, IsNilOrZero(Of("Alice"))) + assert.True(t, IsNilOrZero(Of(0))) + assert.True(t, IsNilOrZero(Of(""))) + assert.True(t, IsNilOrZero[int](nil)) +} + func TestEqual(t *testing.T) { ptr := Of(1) assert.True(t, Equal(ptr, ptr))