Skip to content

Commit

Permalink
feat: Add IsNotNil (#523)
Browse files Browse the repository at this point in the history
* Add IsNotNil

* Apply suggestions from code review

---------

Co-authored-by: Samuel Berthe <[email protected]>
  • Loading branch information
haoxins and samber authored Jan 26, 2025
1 parent 86ce870 commit f1c3379
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 1 deletion.
27 changes: 26 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,7 @@ Conditional helpers:
Type manipulation helpers:

- [IsNil](#isnil)
- [IsNotNil](#isnotnil)
- [ToPtr](#toptr)
- [Nil](#nil)
- [EmptyableToPtr](#emptyabletoptr)
Expand Down Expand Up @@ -1114,7 +1115,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.UniqKeys(map[string]int{"foo": 1, "bar": 2}, map[string]int{"baz": 3})
Expand Down Expand Up @@ -2910,6 +2911,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
lo.IsNotNil(x)
// true

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

var i *int
lo.IsNotNil(i)
// false

var ifaceWithNilValue any = (*string)(nil)
lo.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

0 comments on commit f1c3379

Please sign in to comment.