Iter IterMut And IntoIter Ownership
Pick the iteration mode deliberately: iter borrows read-only, iter_mut borrows mutable for in-place edits, into_iter consumes and hands out ownership.
Code
#[derive(Debug)]
struct Task {
name: String,
done: bool,
}
fn main() {
let mut tasks = vec![
Task { name: String::from("build"), done: false },
Task { name: String::from("test"), done: false },
];
// iter(): borrows &T for read-only traversal; the collection stays intact
for t in tasks.iter() {
println!("read: {}", t.name);
}
println!("still owner of {} tasks", tasks.len());
// iter_mut(): borrows &mut T for in-place edits, moving no Task
for t in tasks.iter_mut() {
t.done = true;
}
println!("{tasks:?}");
// into_iter(): consumes the collection and hands each element over by value
let names: Vec<String> = tasks.into_iter().map(|t| t.name).collect();
println!("moved out: {names:?}");
// tasks has been consumed: reading tasks.len() afterwards no longer compiles
}How the snippet works
One way to read it: the function main, doing all the work.
A single loop drives the file — for t in tasks.iter().
What to watch for
- Runs with what the toolchain already gives you — nothing extra.
Applying it
Entry signature: fn main()
Look for the read:, still owner of, moved out: prefixes when the file runs; they tie each line to its step.
Statements that matter
let names: Vec<String> = tasks.into_iter().map(|t| t.name).collect();
for t in tasks.iter() {
println!("read: {}", t.name);
}
Interactive Tools for This Topic
FAQ
- What does Iter IterMut And IntoIter Ownership print when run?
- No setup needed: run the file and look for labeled lines like `read:`, `still owner of`, `moved out:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.