iter, iter_mut, into_iter in Rust
Three ways to walk a collection: by reference, by mutable reference, by value.
fn main() {
let mut scores = vec![10, 20, 30];
for s in scores.iter() {
print!("{s} ");
}
println!();
for s in scores.iter_mut() {
*s *= 2;
}
println!("{:?}", scores);
let owned: Vec<String> = vec!["a".to_string(), "b".to_string()];
let joined: String = owned.into_iter().collect();
println!("{joined}");
}
How it works
iteryields&Tand leaves the collection intact.iter_mutyields&mut Tso you can edit in place.into_iterconsumes the collection and yields owned values.
Keywords and builtins used here
StringVecfnforinletmainmut
The run, in numbers
- Lines
- 17
- Characters to type
- 309
- Tokens
- 114
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 72 seconds.
Step 3 of 3 in Borrowing, step 6 of 15 in Ownership & borrowing.