golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
120.1k stars 17.24k forks source link

proposal: slices: add transform #67118

Closed lasiar closed 2 weeks ago

lasiar commented 2 weeks ago

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:

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.

seankhliao commented 2 weeks ago

Duplicate of #58881