Skip to content
Open
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
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,7 @@ Type manipulation helpers:
- [EmptyableToPtr](#emptyabletoptr)
- [FromPtr](#fromptr)
- [FromPtrOr](#fromptror)
- [MapPtr](#mapptr)
- [ToSlicePtr](#tosliceptr)
- [FromSlicePtr](#fromsliceptr)
- [FromSlicePtrOr](#fromsliceptror)
Expand Down Expand Up @@ -3646,6 +3647,18 @@ value := lo.FromPtrOr(nil, "empty")
// "empty"
```

### MapPtr

Transforms pointer value if it's non-nil. Otherwise returns nil.
```go
n := 42
value := lo.MapPtr(&n, strconv.Itoa)
// *string{"42"}

value := lo.MapPtr(nil, strconv.Itoa)
// nil
```

### ToSlicePtr

Returns a slice of pointers to each value.
Expand Down
16 changes: 15 additions & 1 deletion type_manipulation.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package lo

import "reflect"
import (
"reflect"
)

// IsNil checks if a value is nil or if it's a reference type with a nil underlying value.
// Play: https://go.dev/play/p/P2sD0PMXw4F
Expand Down Expand Up @@ -68,6 +70,18 @@ func FromPtrOr[T any](x *T, fallback T) T {
return *x
}

// MapPtr transforms pointer value if it's non-nil. Otherwise returns nil.
// Play: https://go.dev/play/p/dL7gZnzB8fX
func MapPtr[T, R any](x *T, transform func(value T) R) *R {
if x == nil {
return nil
}

result := transform(*x)

return &result
Comment on lines +80 to +82

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

return ToPtr(transform(*x))

}

// ToSlicePtr returns a slice of pointers to each value.
// Play: https://go.dev/play/p/P2sD0PMXw4F
func ToSlicePtr[T any](collection []T) []*T {
Expand Down
24 changes: 24 additions & 0 deletions type_manipulation_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package lo

import (
"strconv"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -134,6 +135,29 @@ func TestFromPtrOr(t *testing.T) {
is.Equal(fallbackInt, FromPtrOr(nil, fallbackInt))
}

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

var (
fourtytwo = 42

ptr1 = &fourtytwo
ptr2 *int

fourtytwostring = "42"

expected1 = &fourtytwostring
expected2 *string
)

result1 := MapPtr(ptr1, strconv.Itoa)
result2 := MapPtr(ptr2, strconv.Itoa)

is.Equal(expected1, result1)
is.Equal(expected2, result2)
}

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