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
- The returned iterator borrows
self, soselfmust outlive it. impl Iterator<Item = &str> + '_names that borrow.- No allocation happens: the items are slices into the original.
Keywords and builtins used here
IteratorStringTourVec_fnimplletmainscriptsselfstrstructtitlesvec
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.
Step 2 of 2 in Borrowing without copying, step 6 of 11 in Lifetimes & interior mutability.