-
Notifications
You must be signed in to change notification settings - Fork 18k
Proposal: add generic Filter to slices package #58014
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
Comments
You can just use a for loop, which is more flexible in general. I am not being facetious; the filter operation tends to obscure allocation and overhead, and also tends to be overused. Although I may be in the minority, I do not believe this would be a wise addition to the standard library. |
these were explicitly removed, see #47203 (comment) |
@robpike That makes sense; we are having them in a business layer where the extra overhead is negligent compared with other tasks, but it's true it might be different on lower layers @seankhliao ah ok. Thanks for pointing me in the right direction though. |
@4cq2 Go 1.21 adds |
note the previous comment is misleading, as https://github.com/golang/go/blob/go1.20.4/src/internal/types/testdata/check/slices.go or, you could combine https://pkg.go.dev/slices@master#Clone also here is a function to invert a selection: func Not[E any](fn func(E) bool) func(E) bool {
return func(value E) bool {
return !fn(value)
}
} |
A filter-like function would be useful in Slices package. It is not hard to write manually, but why not to have it in exp/slices (or even in built-in slices package).
This is a first, fizzbuzz-level code, draft, based on what I used locally; there might be a more optimised version.
(What I use locally is actually FilterWithError, with signature
func FilterWithError[E any](s []E, f func(E) (bool, err)) ([]E, err)
), but I think it would not fit into slices package as it is currently.)When I asked on slack, it was recommended me to name it Select/Reject, to make more clear if filter is positive or negative. I think using "filter" is fine, as it is common in other languages and quite clear; Select means something else in Go so it could be confusing.
The text was updated successfully, but these errors were encountered: