In Rust, iterators are essential for traversing collections, and understanding the differences between .iter(), .into_iter(), and .iter_mut() is crucial for effective programming.
.iter()
- Purpose: Creates an iterator that yields immutable references to each element in the collection.
- Ownership: Does not consume the collection; the original collection remains accessible and unmodified.
- Use Case: Ideal when you need to read data without altering the original collection.
Example:
let numbers = vec![1, 2, 3];
for num in numbers.iter() {
println!("{}", num);
}
// `numbers` can still be used here
.into_iter()
- Purpose: Creates an iterator that takes ownership of the collection and yields its elements by value.
- Ownership: Consumes the collection, meaning it cannot be used after the iterator is created.
- Use Case: Suitable when you intend to move the elements out of the collection, especially if the collection is no longer needed afterward.
Example:
let numbers = vec![1, 2, 3];
for num in numbers.into_iter() {
println!("{}", num);
}
// `numbers` is no longer accessible here
.iter_mut()
- Purpose: Creates an iterator that yields mutable references to each element in the collection.
- Ownership: Does not consume the collection but requires a mutable reference to it.
- Use Case: Useful when you need to modify the elements of the collection in place.
Example:
let mut numbers = vec![1, 2, 3];
for num in numbers.iter_mut() {
*num += 1;
}
println!("{:?}", numbers); // Outputs: [2, 3, 4]
Key Differences
.iter(): Yields &T (immutable references).
.into_iter(): Yields T (owned values).
.iter_mut(): Yields &mut T (mutable references).
Choosing the appropriate iterator depends on your specific needs:
- Use
.iter() when you need read-only access to elements.
- Use
.into_iter() when you want to consume the collection and take ownership of its elements.
- Use
.iter_mut() when you need to modify elements in place.
Understanding these distinctions ensures efficient and safe manipulation of collections in Rust.