Borrowing and consuming iterators
Quick answer
An iterator produces items one at a time. Choose iter, iter_mut or into_iter according to whether the caller needs to read, modify or take ownership of elements.
Item ownership
For Vec<T>, iter() yields &T, iter_mut() yields &mut T, and calling into_iter() on an owned vector yields T and consumes the vector. The Iterator trait provides next, which returns Option. A for loop obtains an iterator using IntoIterator and advances it automatically.
fn main() { let mut v = vec![2, 4]; for n in v.iter_mut() { *n += 1; } println!("{v:?}");}Expected stdout (not executed):
[3, 5]The loop updates the existing vector.
fn main() { let names = vec![String::from("Ana"), String::from("Bo")]; let mut items = names.into_iter(); println!("{:?}", items.next()); println!("{:?}", items.next()); println!("{:?}", items.next());}Expected stdout (not executed):
Some("Ana")Some("Bo")NoneThe iterator owns remaining elements; names cannot be used after the move.
Common mistake
Calling into_iter on a borrowed vector has different item types from consuming an owned vector.
Try it yourself
Read the same vector twice using iter, then explain why consuming it prevents another read.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Borrowing and consuming iterators — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
You must double every value in a Vec without consuming it. Which iterator fits?
Borrowing and consuming iterators — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { let mut v = vec![2, 4]; for n in v.iter_mut() { *n += 1; } println!("{v:?}"); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Borrowing and consuming iterators — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { let names = vec![String::from("Ana"), String::from("Bo")]; let mut items = names.into_iter(); println!("{:?}", items.next()); println!("{:?}", items.next()); println!("{:?}", items.next()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.