🚀 Rust Interview Question:
What's the difference between "iter()", "iter_mut()", and "into_iter()"?
Understanding this is essential for mastering Rust ownership and borrowing.
Given:
let v = vec![1, 2, 3];
1. iter()
Creates an iterator over immutable references.
for x in v.iter() {
println!("{}", x);
}
Type:
&i32
Ownership:
✅ Borrowed
Vector usable afterwards:
✅ Yes
Use when:
You only want to read data.
---
2. iter_mut()
Creates an iterator over mutable references.
let mut v = vec![1, 2, 3];
for x in v.iter_mut() {
*x *= 2;
}
Result:
[2, 4, 6]
Type:
&mut i32
Ownership:
✅ Borrowed mutably
Vector usable afterwards:
✅ Yes
Use when:
You want to modify elements in place.
---
3. into_iter()
Consumes the collection and transfers ownership.
let v = vec![1, 2, 3];
for x in v.into_iter() {
println!("{}", x);
}
Type:
i32
Ownership:
❌ Moved
Vector usable afterwards:
❌ No
This won't compile:
println!("{:?}", v);
because ownership was transferred.
---
Quick Summary
iter()
↓
&T
Read Only
iter_mut()
↓
&mut T
Read Modify
into_iter()
↓
T
Takes Ownership
Memory Perspective
iter()
→ No allocation
→ No copies
iter_mut()
→ No allocation
→ In-place mutation
into_iter()
→ Zero-copy ownership transfer
The real lesson:
Rust's iterator APIs are not just about looping.
They are explicit expressions of ownership, borrowing, and mutability.
Once you understand these three methods, a large part of Rust's ownership model starts to click.