#768·lo

Proposal: Add MapPtr function

Author: stepan-tikunovCreated Jan 12, 2026Updated Mar 3, 2026

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:

go
func MapPtr[T, R any](x *T, transform func(value T) R) *R {
	if x == nil {
		return nil
	}

	result := transform(*x)

	return &result
}

Example:

go
// 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.