Skip to content

Commit

Permalink
feat(type_manipulation): add Nil (#383)
Browse files Browse the repository at this point in the history
Co-authored-by: Gustavo Okuyama <[email protected]>
  • Loading branch information
gubtos and Gustavo Okuyama authored Jun 27, 2024
1 parent 0efce40 commit c4d8094
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,7 @@ Type manipulation helpers:

- [IsNil](#isnil)
- [ToPtr](#toptr)
- [Nil](#nil)
- [EmptyableToPtr](#emptyabletoptr)
- [FromPtr](#fromptr)
- [FromPtrOr](#fromptror)
Expand Down Expand Up @@ -2443,6 +2444,15 @@ ptr := lo.ToPtr("hello world")
// *string{"hello world"}
```

### Nil

Returns a nil pointer of type.

```go
ptr := lo.Nil[float64]()
// nil
```

### EmptyableToPtr

Returns a pointer copy of value if it's nonzero.
Expand Down
5 changes: 5 additions & 0 deletions type_manipulation.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ func ToPtr[T any](x T) *T {
return &x
}

// Nil returns a nil pointer of type.
func Nil[T any]() *T {
return nil
}

// EmptyableToPtr returns a pointer copy of value if it's nonzero.
// Otherwise, returns nil pointer.
func EmptyableToPtr[T any](x T) *T {
Expand Down
21 changes: 21 additions & 0 deletions type_manipulation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,27 @@ func TestToPtr(t *testing.T) {
is.Equal(*result1, []int{1, 2})
}

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

nilFloat64 := Nil[float64]()
var expNilFloat64 *float64

nilString := Nil[string]()
var expNilString *string

is.Equal(expNilFloat64, nilFloat64)
is.Nil(nilFloat64)
is.NotEqual(nil, nilFloat64)

is.Equal(expNilString, nilString)
is.Nil(nilString)
is.NotEqual(nil, nilString)

is.NotEqual(nilString, nilFloat64)
}

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

0 comments on commit c4d8094

Please sign in to comment.