Skip to content

proposal: slices: add transform #67118

Not planned
Not planned
@lasiar

Description

@lasiar

Proposal Details

Proposal Details

I propose the following:

func Transform[S ~[]E, E any, T any](sl S, f func(E) T) []T {
	out := make([]T, len(sl))
	for i, t := range sl {
		out[i] = f(t)
	}

	return out
}

Something similar to the method from JS: map.

Using this code, you:

  • never forget to pre-allocate the slice
  • avoid code deduplication

Sample code:

type user struct {
    id int64
}

users := make([]user, 0)

...

sendByIDs(slices.Transform(users, func(u user) int64 {
    return u.id
}))

Naming

I believe that the name "map" could be confusing and may be associated with the type.

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

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @gopherbot@seankhliao@lasiar

        Issue actions

          proposal: slices: add transform · Issue #67118 · golang/go