Skip to content

Add methods Iterator::find_or_{first,nth,last} #3023

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

Closed
wants to merge 1 commit into from
Closed

Add methods Iterator::find_or_{first,nth,last} #3023

wants to merge 1 commit into from

Conversation

z33ky
Copy link

@z33ky z33ky commented Nov 21, 2020

I'm proposing to add the methods find_or_{first,nth,last} to the Iterator trait, to facilitate returning an item that is part of the sequence itself in case no item satisfies the predicate.

Example:

let a = [0, 1, 2, 3];

assert_eq!(a.iter().by_ref().copied().find_or_first(|e| *e == 5   ), Some(0)); // predicate is never satisfied, so `find_or_first` returns the first item (`0`)
assert_eq!(a.iter().by_ref().copied().find_or_nth(  |e| *e == 5, 1), Some(1)); // predicate is never satisfied, so `find_or_nth` returns the 2nd item (`1`) (count begins from `0`)
assert_eq!(a.iter().by_ref().copied().find_or_last( |e| *e == 5   ), Some(3)); // predicate is never satisfied, so `find_or_last` returns the last item (`3`)

Rendered

# Drawbacks
[drawbacks]: #drawbacks

libstd grows.
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I hope this isn't too terse, but that's literally all that'd happen I think.

@sfackler
Copy link
Member

Small API additions do not require RFCs. You can just make a PR against rust-lang/rust with the proposed methods.

@z33ky
Copy link
Author

z33ky commented Nov 21, 2020

Thanks, I opened rust-lang/rust#79271.

@z33ky z33ky closed this Nov 21, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants