What if your computer could handle all the boring, repetitive checking for you in just one simple step?
Why Iterating over collections in Rust? - Purpose & Use Cases
Imagine you have a list of your favorite songs written down on paper. To find the longest song, you have to look at each title one by one, write down its length, and compare it manually. This takes a lot of time and effort, especially if the list is very long.
Doing this by hand is slow and easy to mess up. You might skip a song, misread a length, or forget which one was longest. If the list changes, you have to start all over again. This makes the task frustrating and error-prone.
Using iteration in Rust lets the computer do this repetitive checking for you. You can tell it to look at each item in a collection one by one automatically. This saves time, avoids mistakes, and works even if the list grows or changes.
let mut i = 0; while i < songs.len() { println!("{}", songs[i]); i += 1; }
for song in &songs { println!("{}", song); }
It makes working with many items easy and reliable, letting you focus on what to do with each item instead of how to move through the list.
Think of a grocery list app that shows each item one by one to check off. Iteration helps the app go through the list smoothly, no matter how many items you add or remove.
Manual checking of each item is slow and error-prone.
Iteration automates going through collections efficiently.
It works well even when collections change size or content.
Practice
let numbers = [1, 2, 3];
for num in numbers {
println!("{}", num);
}Solution
Step 1: Understand the for loop over an array
The for loop visits each element in the array named 'numbers'.Step 2: Action inside the loop
Each element is printed on its own line using println! macro.Final Answer:
Prints each number in the array on a new line -> Option BQuick Check:
for loop over array prints elements one by one [OK]
- Thinking arrays can't be iterated
- Expecting the whole array printed at once
- Confusing print! with println!
v in Rust?Solution
Step 1: Recall Rust for loop syntax
Rust uses 'for variable in collection' to iterate over items.Step 2: Check each option
for i in v { println!("{}", i); } matches correct syntax; others use invalid keywords.Final Answer:
for i in v { println!("{}", i); } -> Option AQuick Check:
Rust uses 'for ... in ...' loops [OK]
- Using 'to' instead of 'in'
- Using 'foreach' which is not Rust syntax
- Using 'loop' incorrectly
let v = vec![10, 20, 30];
let mut sum = 0;
for &num in &v {
sum += num;
}
println!("{}", sum);Solution
Step 1: Understand iteration with references
The loop uses '&num in &v' to borrow each element by reference and dereference it with '&num'.Step 2: Calculate sum of elements
sum starts at 0, then adds 10, 20, and 30, resulting in 60.Final Answer:
60 -> Option AQuick Check:
Sum of 10+20+30 = 60 [OK]
- Confusing references and values
- Expecting concatenation instead of sum
- Thinking borrowing causes error here
let arr = [1, 2, 3];
for num in arr {
num += 1;
println!("{}", num);
}Solution
Step 1: Check mutability of loop variable
In Rust, loop variables are immutable by default; 'num' is a copy of array element.Step 2: Understand why 'num += 1' fails
Trying to change 'num' causes error because it is not declared mutable.Final Answer:
Cannot modify 'num' because it is an immutable copy -> Option DQuick Check:
Loop variables are immutable unless declared mutable [OK]
- Thinking semicolon missing causes error
- Believing arrays can't be iterated
- Assuming loop vars are references by default
let words = vec!["apple", "banana", "cherry"];. How do you create a new vector containing the lengths of each word using iteration?Solution
Step 1: Use iterator and map to transform elements
words.iter() creates an iterator over references to strings; map applies a function to each element.Step 2: Collect results into a new vector
collect() gathers the mapped lengths into a Vec<usize>.Final Answer:
let lengths: Vec<usize> = words.iter().map(|w| w.len()).collect(); -> Option CQuick Check:
Use iter().map(...).collect() to transform collections [OK]
- Trying to use for loop as expression
- Using map directly on vector without iter()
- Using for_each which returns () not a collection
Ready to prove it?
Pass the test and this pattern moves unknown
