Rust iterators
From wikinotes
Iterators are lazily evaluated sequences of items.
Like python generators, ruby enumerators, etc.
Iterator Usage
Iterators provide some methods to create new iterators, allowing you to gradually transform the value.
They are lazily evaluated, you'll need to end your chain of iterators with a method that consumes the iterator..next(); // consumes iterator, returning next item .collect(); // consumes iterator, returning all contained elementslet nums = vec![1, 2, 3]; let modified_nums = nums .iter() .map(|x| x + 1) .map(|x| x * 2) .collect();
Implement an Iterator
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"); }