Skip to content

proposal: slices: add transform #67118

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
lasiar opened this issue Apr 30, 2024 · 1 comment
Closed

proposal: slices: add transform #67118

lasiar opened this issue Apr 30, 2024 · 1 comment

Comments

@lasiar
Copy link

lasiar commented Apr 30, 2024

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.

@gopherbot gopherbot added this to the Proposal milestone Apr 30, 2024
@seankhliao
Copy link
Member

Duplicate of #58881

@seankhliao seankhliao marked this as a duplicate of #58881 Apr 30, 2024
@seankhliao seankhliao closed this as not planned Won't fix, can't repro, duplicate, stale Apr 30, 2024
@golang golang locked and limited conversation to collaborators Apr 30, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants