Rust iterators: Difference between revisions
From wikinotes
(Created page with "Iterators are lazily evaluated sequences of items.<br> Like python generators, ruby enumerators, etc. = Example = <blockquote> <syntaxhighlight lang="rust"> </syntaxhighlight> </blockquote><!-- Example -->") |
|||
Line 4: | Line 4: | ||
= Example = | = Example = | ||
<blockquote> | <blockquote> | ||
This will keep on iterating over weekdays infinitely. | |||
<syntaxhighlight lang="rust"> | <syntaxhighlight lang="rust"> | ||
#[derive(Debug)] | |||
enum Weekday { | |||
MON = 0, | |||
TUE, | |||
WED, | |||
THU, | |||
FRI, | |||
SAT, | |||
SUN, | |||
} | |||
impl Iterator for Weekday { | |||
type Item = Weekday; | |||
fn next(&mut self) -> Option<Self::Item> { | |||
let day = match self { | |||
Weekday::MON => Weekday::TUE, | |||
Weekday::TUE => Weekday::WED, | |||
Weekday::WED => Weekday::THU, | |||
Weekday::THU => Weekday::FRI, | |||
Weekday::FRI => Weekday::SAT, | |||
Weekday::SAT => Weekday::SUN, | |||
Weekday::SUN => Weekday::MON, | |||
}; | |||
Some(day) | |||
} | |||
} | |||
fn main() { | |||
let mut day = Weekday::SAT; | |||
day.next(); | |||
day.next(); | |||
matches!(day, Weekday::MON); | |||
println!("success"); | |||
} | |||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- Example --> | </blockquote><!-- Example --> |
Revision as of 19:27, 9 February 2023
Iterators are lazily evaluated sequences of items.
Like python generators, ruby enumerators, etc.
Example
This will keep on iterating over weekdays infinitely.
#[derive(Debug)] enum Weekday { MON = 0, TUE, WED, THU, FRI, SAT, SUN, } impl Iterator for Weekday { type Item = Weekday; fn next(&mut self) -> Option<Self::Item> { let day = match self { Weekday::MON => Weekday::TUE, Weekday::TUE => Weekday::WED, Weekday::WED => Weekday::THU, Weekday::THU => Weekday::FRI, Weekday::FRI => Weekday::SAT, Weekday::SAT => Weekday::SUN, Weekday::SUN => Weekday::MON, }; Some(day) } } fn main() { let mut day = Weekday::SAT; day.next(); day.next(); matches!(day, Weekday::MON); println!("success"); }