Skip to content

Commit

Permalink
feat(type_manipulation): add Nil
Browse files Browse the repository at this point in the history
  • Loading branch information
Gustavo Okuyama committed Oct 5, 2023
1 parent 2a74434 commit 8eb5f98
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 @@ -217,6 +217,7 @@ Conditional helpers:
Type manipulation helpers:

- [ToPtr](#toptr)
- [Nil](#nil)
- [EmptyableToPtr](#emptyabletoptr)
- [FromPtr](#fromptr)
- [FromPtrOr](#fromptror)
Expand Down Expand Up @@ -2164,6 +2165,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 @@ -7,6 +7,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 @@ -15,6 +15,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 8eb5f98

Please sign in to comment.