Skip to content

Proposal: Add MapPtr function #768

Description

@stepan-tikunov

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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions