Okay, let's break down the differences between .iter(), .into_iter(), and other ways to create iterators in Rust, focusing on what they do with ownership and mutability:
Understanding Iterators in Rust
Iterators in Rust are a way to access a sequence of values (e.g., elements of a vector, characters in a string) one at a time. They implement the Iterator trait, which requires a next() method that returns an Option<Item>, where Item is the type of the elements being yielded. When the iterator is exhausted, next() returns None.
1. .iter(): Immutable Borrowing
- Purpose: Creates an iterator that yields immutable references to the elements of the collection.
- Ownership: Does not take ownership of the collection. It only borrows it immutably.
- Mutability: You cannot modify the original collection while the iterator is active, because it's borrowed immutably.
- Use Case: When you want to iterate over the elements of a collection without modifying them.
let numbers = vec![1, 2, 3];
for &number in numbers.iter() { // Note the '&' to dereference the reference
println!("Number: {}", number);
}
// numbers is still valid here and can be used because .iter() only borrowed it.
println!("Original vector: {:?}", numbers);
2. .into_iter(): Moving or Consuming
- Purpose: Creates an iterator that either moves or consumes the elements of the collection, depending on the type of the collection and the elements.
- Ownership: Takes ownership of the collection (or, in some cases, its elements). The original collection is no longer usable after you call
.into_iter().
- Mutability: You get ownership of the elements, so you can modify them if they are mutable.
- Use Case: When you want to process the elements of a collection and you no longer need the original collection itself. Often used when you want to transform the elements into a new collection.
let numbers = vec![1, 2, 3];
for number in numbers.into_iter() { // 'number' owns the value each time
println!("Number: {}", number);
}
// numbers is now invalid because it was moved into the iterator
// println!("Original vector: {:?}", numbers); // This would cause a compile error
// Example with a new collection
let numbers2 = vec![1, 2, 3];
let doubled: Vec<i32> = numbers2.into_iter().map(|x| x * 2).collect(); // Collects into a new vector
println!("Doubled vector: {:?}", doubled);
3. .iter_mut(): Mutable Borrowing
- Purpose: Creates an iterator that yields mutable references to the elements of the collection.
- Ownership: Does not take ownership of the collection, but it borrows it mutably.
- Mutability: You can modify the elements of the original collection through the mutable references provided by the iterator.
- Use Case: When you need to modify the elements of a collection in place.
let mut numbers = vec![1, 2, 3];
for number in numbers.iter_mut() {
*number *= 2; // Multiply each element by 2 (dereference the mutable reference)
}
println!("Modified vector: {:?}", numbers); // Output: [2, 4, 6]
4. Other Ways to Create Iterators:
-
Range:
for i in 0..5 { // Creates an iterator from 0 to 4 (exclusive)
println!("{}", i);
}
-
std::iter::repeat: Creates an infinite iterator that repeats a value.
use std::iter;
for i in iter::repeat(5).take(3) { // Repeats 5 three times
println!("{}", i); // Output: 5 5 5
}
-
std::iter::once: Creates an iterator that yields a single value.
use std::iter;
for i in iter::once(10) {
println!("{}", i); // Output: 10
}
-
Custom Iterators: You can implement the Iterator trait for your own types to create custom iterators. This is more advanced but gives you complete control over how the iteration works.
Key Differences Summarized
| Method | Ownership Taken? | Yields | Mutability of Elements | Collection Modified? |
|---|
.iter() | No | Immutable Refs | No | No |
.into_iter() | Yes | Values (moved/copied) | Yes (if moved value is mutable) | Collection is consumed |
.iter_mut() | No | Mutable Refs | Yes | Yes |
In Simple Terms
iter(): "Just look at the things."
into_iter(): "Take the things and do something with them (the original is gone)."
iter_mut(): "Look at the things and change them."
Understanding these distinctions is crucial for writing correct and efficient Rust code, especially when dealing with ownership and borrowing. Choose the iterator method that best reflects your intent for how you want to handle the data within the collection.