iter() / iter_mut() / into_iter()
There are three ways to get an iterator from a collection. The method you use depends on whether you want immutable references, mutable references, or ownership of the elements.
Syntax
// Creates an iterator that yields immutable references (&T) to each element.
for item in collection.iter() { }
// Creates an iterator that yields mutable references (&mut T) to each element.
for item in collection.iter_mut() { }
// Creates an iterator that takes ownership (T) of each element (the collection is consumed).
for item in collection.into_iter() { }
// A for loop automatically calls into_iter() via the IntoIterator trait.
for item in &collection { } // Equivalent to iter().
for item in &mut collection { } // Equivalent to iter_mut().
for item in collection { } // Equivalent to into_iter().
Method List
| Method / Syntax | Element Type | Description |
|---|---|---|
| iter() | &T | Yields immutable references. The collection retains ownership and remains usable after the loop. |
| iter_mut() | &mut T | Yields mutable references. You can modify element values inside the loop. |
| into_iter() | T | Transfers ownership of each element. The collection cannot be used after the call. |
| &collection | &T | Behaves the same as iter() in a for loop. This is the most common pattern. |
| &mut collection | &mut T | Behaves the same as iter_mut() in a for loop. |
Sample Code
fn main() {
let mut numbers = vec![1, 2, 3, 4, 5];
// iter(): Loops with immutable references. numbers is still usable after the loop.
for n in numbers.iter() {
print!("{} ", n); // n is &i32.
}
println!();
// &collection is equivalent to iter().
for n in &numbers {
print!("{} ", n);
}
println!();
// iter_mut(): Loops with mutable references and modifies values.
for n in numbers.iter_mut() {
*n *= 2; // Dereference and double the value.
}
println!("{:?}", numbers); // [2, 4, 6, 8, 10]
// into_iter(): Moves ownership of each element.
let words = vec!["hello", "world"];
for word in words.into_iter() {
print!("{} ", word); // Ownership of the String moves into word.
}
println!();
// Trying to use words here would cause a compile error.
// Example of using iter() with an array.
let arr = [10, 20, 30];
let doubled: Vec<i32> = arr.iter().map(|&x| x * 2).collect();
println!("{:?}", doubled); // [20, 40, 60]
}
Notes
The choice between the three iterator methods depends on two questions: "Do you need the collection after the loop?" and "Do you need to modify the elements?" In most cases, use the read-only iter() (or &collection). Once you call into_iter(), the collection loses its ownership, so any attempt to access it after the loop results in a compile error.
Rust's for loop uses the IntoIterator trait internally. A reference like &vec implements IntoIterator for a reference to Vec, automatically behaving like iter(). In practice, for x in &vec is the most commonly seen pattern.
If you find any errors or copyright issues, please contact us.