Not planned
Description
HI! In order to improve development efficiency, I believe it is necessary to provide more popular array slices functions, including but not limited to the following item:
- Filter: returns the elements matched, it may be like this:
func Filter[S ~[]T, T any](s S, f func(T) bool) (r S) {
for i := range s {
if f(s[i]) {
r = append(r, s[i])
}
}
return r
}
- Map: returns the new elements converted, it may be like this:
func Map[S ~[]T, M []N, T, N any](s S, f func(T) N) (m M) {
m = make(M, len(s))
for i := range s {
m[i] = f(s[i])
}
return m
}
- Delete: remove the indexed element, it may be like this:
Attention! what the Delete function is in go now has a bug!! like this:
s := []int{0, 1, 2}
fmt.Println(slices.Delete(s, 1, 2)) // [0,2]
fmt.Println(s) // [0,2,2] Terrifying! I don't think that `s` become [0,2,2] is your want!!!
// BTW! If you do not accept the proposal, please also modify the Delete function. maybe like this:
r = make(S, len(s)-1)
copy(r, s[:i])
copy(r[i:], s[i+1:])
// here is a fixed version, it can be use like slices.Delete(s, len(s)-1) or slices.Delete(s,-1)
func Delete[S ~[]T, T any](s S, i int) (r S) {
if i < 0 {
return deleteByIndex(s, len(s)+i)
}
return deleteByIndex(s, i)
}
func deleteByIndex[S ~[]T, T any](s S, i int) (r S) {
switch i {
case 0:
r = s[1:]
case len(s) - 1:
r = s[:i]
default:
r = make(S, len(s)-1)
copy(r, s[:i])
copy(r[i:], s[i+1:])
}
return
}
Looking forward to your reply.
Metadata
Metadata
Assignees
Type
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity
dominikh commentedon Jul 10, 2023
1 and 2 were previously rejected, see #47203 (comment).
3 exists as an in-place operation, see https://pkg.go.dev/slices@master#Delete.
aitimate commentedon Jul 10, 2023
Delete is a bug function, are you serious?
aitimate commentedon Jul 10, 2023
ianlancetaylor commentedon Jul 11, 2023
We plan to first develop a plan for iterators (see the earlier discussion at #54245). Once we understand whether or how iterators should be available in Go, we can consider what a general
Filter
orMap
function might look like. We want to avoid moving too fast and winding up with differing versions of these functions.Map
andFilter
#68065