typestar

Returning a borrowing iterator in Rust

An iterator over borrowed data ties its lifetime to the collection.

struct Tour {
    steps: Vec<String>,
}

impl Tour {
    fn titles(&self) -> impl Iterator<Item = &str> + '_ {
        self.steps.iter().map(|s| s.as_str())
    }

    fn scripts(&self) -> impl Iterator<Item = &String> + '_ {
        self.steps.iter().filter(|s| s.ends_with(".rs"))
    }
}

fn main() {
    let tour = Tour {
        steps: vec!["Slices".to_string(), "shapes.rs".to_string()],
    };
    println!("{:?}", tour.titles().collect::<Vec<&str>>());
    println!("{}", tour.scripts().count());
}

How it works

  1. The returned iterator borrows self, so self must outlive it.
  2. impl Iterator<Item = &str> + '_ names that borrow.
  3. No allocation happens: the items are slices into the original.

Keywords and builtins used here

The run, in numbers

Lines
21
Characters to type
446
Tokens
174
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 99 seconds.

Type this snippet

Step 2 of 2 in Borrowing without copying, step 6 of 11 in Lifetimes & interior mutability.

← Previous Next →