What is the simplest way to loop over all elements in a vector in Rust?
Use a for loop with the vector's iterator, like for item in &vec { ... }. This lets you access each element one by one.
Click to reveal answer
beginner
What does the iter() method do on a collection in Rust?
It creates an iterator that lets you read each element by reference without taking ownership, so you can loop over the collection safely.
Click to reveal answer
intermediate
How do you get mutable access to elements while iterating over a vector?
Use iter_mut() to get a mutable iterator. Then inside the loop, you can change each element directly.
Click to reveal answer
intermediate
What is the difference between into_iter() and iter()?
into_iter() takes ownership and consumes the collection, moving elements out. iter() only borrows elements by reference without consuming.
Click to reveal answer
beginner
Can you use a for loop directly on arrays and slices in Rust?
Yes! Arrays and slices implement the IntoIterator trait, so you can loop over them with for item in &array_or_slice.
Click to reveal answer
Which method gives you a mutable iterator over a vector?
Amut_iter()
Biter()
Citer_mut()
Dinto_iter()
✗ Incorrect
iter_mut() returns a mutable iterator allowing you to modify elements.
What happens when you use into_iter() on a vector?
AIt borrows elements immutably
BIt consumes the vector and moves elements out
CIt creates a mutable borrow
DIt clones the vector
✗ Incorrect
into_iter() takes ownership and consumes the vector, moving elements.
How do you loop over elements without taking ownership?
Afor item in vec.iter_mut()
Bfor item in vec
Cfor item in vec.into_iter()
Dfor item in &vec
✗ Incorrect
Using &vec borrows the vector, so you don't take ownership.
Which trait allows arrays to be used in a for loop?
AIntoIterator
BClone
CCopy
DIterator
✗ Incorrect
Arrays implement IntoIterator, enabling for loops.
What is the type of elements yielded by iter() on a vector of i32?
A&i32
Bi32
C&mut i32
DBox<i32>
✗ Incorrect
iter() yields references to elements, so &i32.
Explain how to iterate over a vector in Rust to read and modify its elements.
Think about borrowing rules and iterator methods.
You got /5 concepts.
Describe the difference between iter(), iter_mut(), and into_iter() when used on collections.
Focus on how each method treats ownership and mutability.
You got /4 concepts.
Practice
(1/5)
1. What does the following Rust code do?
let numbers = [1, 2, 3];
for num in numbers {
println!("{}", num);
}
easy
A. Causes a compile error because arrays can't be iterated
B. Prints each number in the array on a new line
C. Prints the whole array as one line
D. Prints the length of the array
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 B
Quick Check:
for loop over array prints elements one by one [OK]
Hint: For loops visit each item in order [OK]
Common Mistakes:
Thinking arrays can't be iterated
Expecting the whole array printed at once
Confusing print! with println!
2. Which of these is the correct syntax to iterate over a vector named v in Rust?
easy
A. for i in v { println!("{}", i); }
B. for i to v { println!("{}", i); }
C. foreach i in v { println!("{}", i); }
D. loop i in v { println!("{}", i); }
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 A
Quick Check:
Rust uses 'for ... in ...' loops [OK]
Hint: Remember: for variable in collection [OK]
Common Mistakes:
Using 'to' instead of 'in'
Using 'foreach' which is not Rust syntax
Using 'loop' incorrectly
3. What is the output of this Rust code?
let v = vec![10, 20, 30];
let mut sum = 0;
for &num in &v {
sum += num;
}
println!("{}", sum);
medium
A. 60
B. 303020
C. Error due to borrowing
D. 0
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 A
Quick Check:
Sum of 10+20+30 = 60 [OK]
Hint: Sum elements by iterating with references [OK]
Common Mistakes:
Confusing references and values
Expecting concatenation instead of sum
Thinking borrowing causes error here
4. Identify the error in this Rust code snippet:
let arr = [1, 2, 3];
for num in arr {
num += 1;
println!("{}", num);
}
medium
A. Loop variable 'num' must be a reference
B. Syntax error: missing semicolon after println!
C. Array cannot be iterated directly
D. Cannot modify 'num' because it is an immutable copy
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 D
Quick Check:
Loop variables are immutable unless declared mutable [OK]
Hint: Loop vars are immutable unless 'mut' used [OK]
Common Mistakes:
Thinking semicolon missing causes error
Believing arrays can't be iterated
Assuming loop vars are references by default
5. You have a vector of strings: let words = vec!["apple", "banana", "cherry"];. How do you create a new vector containing the lengths of each word using iteration?
hard
A. let lengths = words.map(|w| w.len());
B. let lengths = for w in words { w.len() };
C. let lengths: Vec<usize> = words.iter().map(|w| w.len()).collect();
D. let lengths = words.iter().for_each(|w| w.len());
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 C
Quick Check:
Use iter().map(...).collect() to transform collections [OK]
Hint: Use iter().map(...).collect() to build new collections [OK]
Common Mistakes:
Trying to use for loop as expression
Using map directly on vector without iter()
Using for_each which returns () not a collection
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.