mirror of
https://github.com/samber/lo.git
synced 2025-10-16 04:50:39 +08:00
Add IsNil function for checking nil values in Go (#399)
This commit is contained in:

committed by
GitHub

parent
8f90a520e8
commit
2bbb3ea5f7
@@ -7,6 +7,12 @@ func ToPtr[T any](x T) *T {
|
||||
return &x
|
||||
}
|
||||
|
||||
// IsNil checks if a value is nil or if it's a reference type with a nil underlying value.
|
||||
func IsNil(x any) bool {
|
||||
defer func() { recover() }()
|
||||
return x == nil || reflect.ValueOf(x).IsNil()
|
||||
}
|
||||
|
||||
// EmptyableToPtr returns a pointer copy of value if it's nonzero.
|
||||
// Otherwise, returns nil pointer.
|
||||
func EmptyableToPtr[T any](x T) *T {
|
||||
|
@@ -15,6 +15,30 @@ func TestToPtr(t *testing.T) {
|
||||
is.Equal(*result1, []int{1, 2})
|
||||
}
|
||||
|
||||
func TestIsNil(t *testing.T) {
|
||||
t.Parallel()
|
||||
is := assert.New(t)
|
||||
|
||||
var x int
|
||||
is.False(IsNil(x))
|
||||
|
||||
var k struct{}
|
||||
is.False(IsNil(k))
|
||||
|
||||
var s *string
|
||||
is.True(IsNil(s))
|
||||
|
||||
var i *int
|
||||
is.True(IsNil(i))
|
||||
|
||||
var b *bool
|
||||
is.True(IsNil(b))
|
||||
|
||||
var ifaceWithNilValue interface{} = (*string)(nil)
|
||||
is.True(IsNil(ifaceWithNilValue))
|
||||
is.True(ifaceWithNilValue != nil)
|
||||
}
|
||||
|
||||
func TestEmptyableToPtr(t *testing.T) {
|
||||
t.Parallel()
|
||||
is := assert.New(t)
|
||||
|
Reference in New Issue
Block a user