Proposal: Add MapPtr function
What it does:
Safely transforms a value inside a pointer. If the input pointer is nil, returns nil. Otherwise applies the transform function and returns a pointer to the result.
Code:
func MapPtr[T, R any](x *T, transform func(value T) R) *R {
if x == nil {
return nil
}
result := transform(*x)
return &result
}
Example:
// Old way
var userName *string
if user != nil {
name := strings.ToUpper(user.Name)
userName = &name
}
// With MapPtr
userName := lo.MapPtr(user, func(u User) string {
return strings.ToUpper(u.Name)
})
Why we need this:
- Removes error-prone boilerplate nil checks when working with optional values
- Completes the
Map family: Map (slice), MapValues (map), MapPtr (pointer)
- Follows lo's philosophy: simple, pure, generic
- Practical for real-world scenarios with optional data
Small addition, big impact on code clarity.
Proposal: Add
MapPtrfunctionWhat it does:
Safely transforms a value inside a pointer. If the input pointer is nil, returns nil. Otherwise applies the transform function and returns a pointer to the result.
Code:
Example:
Why we need this:
Mapfamily:Map(slice),MapValues(map),MapPtr(pointer)Small addition, big impact on code clarity.