Rust iterators: Difference between revisions

From wikinotes
No edit summary
 
Line 1: Line 1:
Iterators are lazily evaluated sequences of items.<br>
Iterators are lazily evaluated sequences of items.<br>
Like python generators, ruby enumerators, etc.
Like python generators, ruby enumerators, etc.
= Iterator Usage =
<blockquote>
Iterators provide some methods to create new iterators, allowing you to gradually transform the value.<br>
They are lazily evaluated, you'll need to end your chain of iterators with a method that '''consumes''' the iterator.
<syntaxhighlight lang="rust">
.next();    // consumes iterator, returning next item
.collect(); // consumes iterator, returning all contained elements
</syntaxhighlight>
<syntaxhighlight lang="rust">
let nums = vec![1, 2, 3];
let modified_nums = nums
  .iter()
  .map(|x| x + 1)
  .map(|x| x * 2)
  .collect();
</syntaxhighlight>
</blockquote><!-- Iterator Usage -->


= Implement an Iterator =
= Implement an Iterator =

Latest revision as of 20:18, 9 February 2023

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 elements
let 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");
}