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

feat: Add IsNotNil #523

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
27 changes: 26 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,7 @@ Conditional helpers:
Type manipulation helpers:

- [IsNil](#isnil)
- [IsNotNil](#isnotnil)
- [ToPtr](#toptr)
- [Nil](#nil)
- [EmptyableToPtr](#emptyabletoptr)
Expand Down Expand Up @@ -1062,7 +1063,7 @@ keys := lo.Keys(map[string]int{"foo": 1, "bar": 2}, map[string]int{"bar": 3})

### UniqKeys

Creates an array of unique map keys.
Creates an array of unique map keys.

```go
keys := lo.Keys(map[string]int{"foo": 1, "bar": 2}, map[string]int{"baz": 3})
Expand Down Expand Up @@ -2661,6 +2662,30 @@ ifaceWithNilValue == nil
// false
```

### IsNotNil

Checks if a value is not nil or if it's not a reference type with a nil underlying value.

```go
var x int
IsNotNil(x)
// true

var k struct{}
IsNotNil(k)
// true

var i *int
IsNotNil(i)
// false

var ifaceWithNilValue any = (*string)(nil)
IsNotNil(ifaceWithNilValue)
// false
ifaceWithNilValue == nil
// true
```

### ToPtr

Returns a pointer copy of the value.
Expand Down
5 changes: 5 additions & 0 deletions type_manipulation.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ func IsNil(x any) bool {
return x == nil || reflect.ValueOf(x).IsNil()
}

// IsNotNil checks if a value is not nil or if it's not a reference type with a nil underlying value.
func IsNotNil(x any) bool {
return !IsNil(x)
}

// ToPtr returns a pointer copy of value.
func ToPtr[T any](x T) *T {
return &x
Expand Down
24 changes: 24 additions & 0 deletions type_manipulation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,30 @@ func TestIsNil(t *testing.T) {
is.False(ifaceWithNilValue == nil) //nolint:staticcheck
}

func TestIsNotNil(t *testing.T) {
t.Parallel()
is := assert.New(t)

var x int
is.True(IsNotNil(x))

var k struct{}
is.True(IsNotNil(k))

var s *string
is.False(IsNotNil(s))

var i *int
is.False(IsNotNil(i))

var b *bool
is.False(IsNotNil(b))

var ifaceWithNilValue any = (*string)(nil) //nolint:staticcheck
is.False(IsNotNil(ifaceWithNilValue))
is.True(ifaceWithNilValue != nil) //nolint:staticcheck
}

func TestToPtr(t *testing.T) {
t.Parallel()
is := assert.New(t)
Expand Down