Skip to content

Commit

Permalink
Add EmptyableToPtr (#311)
Browse files Browse the repository at this point in the history
* Add EmptyableToPtr
  • Loading branch information
senago committed Mar 20, 2023
1 parent 9ec076e commit 56f34e0
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
20 changes: 20 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)
- [EmptyableToPtr](#emptyabletoptr)
- [FromPtr](#fromptr)
- [FromPtrOr](#fromptror)
- [ToSlicePtr](#tosliceptr)
Expand Down Expand Up @@ -2163,6 +2164,25 @@ ptr := lo.ToPtr("hello world")
// *string{"hello world"}
```

### EmptyableToPtr

Returns a pointer copy of value if it's nonzero.
Otherwise, returns nil pointer.

```go
ptr := lo.EmptyableToPtr[[]int](nil)
// nil

ptr := lo.EmptyableToPtr[string]("")
// nil

ptr := lo.EmptyableToPtr[[]int]([]int{})
// *[]int{}

ptr := lo.EmptyableToPtr[string]("hello world")
// *string{"hello world"}
```

### FromPtr

Returns the pointer value or empty.
Expand Down
13 changes: 13 additions & 0 deletions type_manipulation.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,23 @@
package lo

import "reflect"

// ToPtr returns a pointer copy of value.
func ToPtr[T any](x T) *T {
return &x
}

// EmptyableToPtr returns a pointer copy of value if it's nonzero.
// Otherwise, returns nil pointer.
func EmptyableToPtr[T any](x T) *T {
isZero := reflect.ValueOf(&x).Elem().IsZero()
if isZero {
return nil
}

return &x
}

// FromPtr returns the pointer value or empty.
func FromPtr[T any](x *T) T {
if x == nil {
Expand Down
18 changes: 18 additions & 0 deletions type_manipulation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,24 @@ func TestToPtr(t *testing.T) {
is.Equal(*result1, []int{1, 2})
}

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

is.Nil(EmptyableToPtr(0))
is.Nil(EmptyableToPtr(""))
is.Nil(EmptyableToPtr[[]int](nil))
is.Nil(EmptyableToPtr[map[int]int](nil))
is.Nil(EmptyableToPtr[error](nil))

is.Equal(*EmptyableToPtr(42), 42)
is.Equal(*EmptyableToPtr("nonempty"), "nonempty")
is.Equal(*EmptyableToPtr([]int{}), []int{})
is.Equal(*EmptyableToPtr([]int{1, 2}), []int{1, 2})
is.Equal(*EmptyableToPtr(map[int]int{}), map[int]int{})
is.Equal(*EmptyableToPtr(assert.AnError), assert.AnError)
}

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

0 comments on commit 56f34e0

Please sign in to comment.