-
Notifications
You must be signed in to change notification settings - Fork 18k
proposal: slices: Add Find #71536
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
We already have https://pkg.go.dev/slices#IndexFunc. |
I have this code: var prev *github.CheckRun
for _, r := range res.CheckRuns {
if r.GetName() == "mergelock" {
prev = r
break
}
} Using var prev *github.CheckRun
prevIdx := slices.IndexFunc(res.CheckRuns, func(r *github.CheckRun) bool {
return r.GetName() == "mergelock"
})
if prevIdx >= 0 {
prev = res.CheckRuns[prevIdx]
} It would be nice if I could write: prev, _ := slices.Find(res.CheckRuns, func(r *github.CheckRun) bool {
return r.GetName() == "mergelock"
}) |
Related Issues (Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.) |
To make any argument for adding this function when we already have |
Here's an example: go/src/crypto/tls/key_agreement.go Lines 170 to 180 in 37f27fb
This could be rewritten as follows: curveID, ok := slices.Find(clientHello.supportedCurves, func(c CurveID) bool {
return config.supportsCurve(ka.version, c)
})
if !ok {
return nil, errors.New("tls: no supported elliptic curves offered")
} Here are some others: Lines 504 to 513 in 37f27fb
go/src/runtime/pprof/protomem_test.go Lines 216 to 225 in 37f27fb
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
|
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 |
see previously #52006 (comment) |
This is not correct. In a lot of cases the check is unnecessary and may be omitted. |
@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. |
Proposal Details
A function for finding the first value in a slice which satisfies a predicate function.
The text was updated successfully, but these errors were encountered: