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(type_manipulation): add Nil #383

Merged
merged 2 commits into from
Jun 27, 2024
Merged
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
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