IntoIterator For Borrowed Structs
Implement IntoIterator for a reference so for loops receive borrowed items, the collection survives the loop, and generic fns can consume &shelf directly.
Code
struct Shelf {
books: Vec<String>,
}
// 为引用实现 IntoIterator:for 循环拿到的是借用的元素,集合不被消耗
impl<'a> IntoIterator for &'a Shelf {
type Item = &'a String;
type IntoIter = std::slice::Iter<'a, String>;
fn into_iter(self) -> Self::IntoIter {
self.books.iter()
}
}
fn count<I: IntoIterator>(items: I) -> usize {
items.into_iter().count()
}
fn main() {
let shelf = Shelf {
books: vec!["ownership".into(), "borrowing".into(), "iterators".into()],
};
// &shelf 自动走进我们的实现:元素是 &String
for book in &shelf {
println!("reading: {book}");
}
// 循环后集合完整无损,还能继续用
println!("still holds {} books", shelf.books.len());
println!("counted {}", count(&shelf));
}Inside the snippet
Structurally, expect the functions into_iter, count and main and nothing else.
One loop does the cycling here: for book in &shelf.
Watch out for
- Runs with what the toolchain already gives you — nothing extra.
Using it
Declared as fn into_iter(self) -> Self::IntoIter
Each run prints the 3 labeled blocks reading:, still holds, counted in source order.
Execute the file and main walks through count, in that order.
Key statements
fn count<I: IntoIterator>(items: I) -> usize {
items.into_iter().count()
}
fn into_iter(self) -> Self::IntoIter {
self.books.iter()
}
Interactive Tools for This Topic
FAQ
- What does IntoIterator For Borrowed Structs print when run?
- Run it as a complete program — the output lines carry labels such as `reading:`, `still holds`, `counted`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.