Duplicate of#52006
Description
Proposal Details
A function for finding the first value in a slice which satisfies a predicate function.
package slices
// Find returns the first value satisfying f.
// The second return value reports whether a value was found.
func Find[S ~[]E, E any](s S, f func(E) bool) (E, bool) {
for _, v := range s {
if f(v) {
return v, true
}
}
var z E
return z, false
}
Metadata
Metadata
Assignees
Labels
Type
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity
ianlancetaylor commentedon Feb 3, 2025
We already have https://pkg.go.dev/slices#IndexFunc.
icholy commentedon Feb 3, 2025
I have this code:
Using
slices.IndexFunc
looks like this (which is the same number of lines and harder to read):It would be nice if I could write:
gabyhelp commentedon Feb 3, 2025
Related Issues
(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)
ianlancetaylor commentedon Feb 3, 2025
To make any argument for adding this function when we already have
IndexFunc
, it would be good to see examples in existing Go code (code that you didn't write) where it could be used to simplify the code. Thanks.icholy commentedon Feb 3, 2025
Here's an example:
go/src/crypto/tls/key_agreement.go
Lines 170 to 180 in 37f27fb
This could be rewritten as follows:
Here are some others:
go/src/debug/pe/file_test.go
Lines 504 to 513 in 37f27fb
go/src/runtime/pprof/protomem_test.go
Lines 216 to 225 in 37f27fb
go/src/os/stat_test.go
Lines 99 to 109 in 37f27fb
go/src/cmd/link/internal/ld/elf_test.go
Lines 357 to 370 in 37f27fb
go/src/cmd/link/internal/ld/dwarf_test.go
Lines 492 to 501 in 37f27fb
go/src/cmd/internal/objfile/goobj.go
Lines 48 to 54 in 37f27fb
go/src/cmd/go/internal/work/buildid.go
Lines 279 to 288 in 37f27fb
Agent-Hellboy commentedon Feb 3, 2025
I don't have much experience, but I don't think we should bloat the standard libraries or add new built-in function, just for cleaner code. Look at the heap library, I'm becoming fan of Go because of its simplicity.
All of the example code you have shared from go code base is pleasing to my eye. There is no need of
Find
seankhliao commentedon Feb 3, 2025
see previously #52006 (comment)
icholy commentedon Feb 3, 2025
This is not correct. In a lot of cases the check is unnecessary and may be omitted.
ianlancetaylor commentedon Feb 3, 2025
@icholy Thanks for the example, but I have to say that if somebody sent me a patch to change the current code in key_agreement.go to use your suggested replacement, I would reject the patch. The original code is longer but to me it seems clearer.