Bird
Raised Fist0
Rustprogramming~20 mins

Iterating over collections in Rust - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Rust Iteration Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of iterating and modifying a vector
What is the output of this Rust code snippet?
Rust
fn main() {
    let mut nums = vec![1, 2, 3, 4];
    for x in &mut nums {
        *x += 2;
    }
    println!("{:?}", nums);
}
ACompilation error due to mutable borrow
B[1, 2, 3, 4]
C[2, 3, 4, 5]
D[3, 4, 5, 6]
Attempts:
2 left
💡 Hint
Remember that iterating with &mut allows modifying elements in place.
❓ Predict Output
intermediate
2:00remaining
Output of iterating over a HashMap
What does this Rust program print?
Rust
use std::collections::HashMap;
fn main() {
    let mut map = HashMap::new();
    map.insert("a", 1);
    map.insert("b", 2);
    map.insert("c", 3);
    let mut sum = 0;
    for (_, v) in &map {
        sum += v;
    }
    println!("{}", sum);
}
A6
B123
Cabc
DCompilation error due to borrowing
Attempts:
2 left
💡 Hint
Sum all values in the map by iterating over references.
🔧 Debug
advanced
2:00remaining
Why does this iterator code fail to compile?
Consider this Rust code snippet. Why does it fail to compile?
Rust
fn main() {
    let v = vec![1, 2, 3];
    let iter = v.iter();
    for i in iter {
        v.push(*i + 1);
    }
}
ASyntax error: missing semicolon after `v.iter()`
BCannot borrow `v` as mutable because it is already borrowed as immutable by `iter`
CRuntime error: vector capacity exceeded
DNo error, code runs and prints the vector
Attempts:
2 left
💡 Hint
Think about Rust's borrowing rules when iterating and modifying the same collection.
📝 Syntax
advanced
2:00remaining
Which option correctly iterates over a vector and prints each element?
Choose the Rust code snippet that compiles and prints each element of the vector `v`.
Rust
let v = vec![10, 20, 30];
A
for i in v.iter_mut() {
    println!("{}", i);
}
B
for i in &v {
    println!("{}", i);
}
C
for i in v.iter() {
    println!("{}", *i);
}
D
for i in v {
    println!("{}", i);
}
Attempts:
2 left
💡 Hint
Remember that iter() returns references, so you may need to dereference.
🚀 Application
expert
2:00remaining
Count how many elements in a vector are even using iterator methods
Which Rust code snippet correctly counts the number of even integers in the vector `nums`?
Rust
let nums = vec![1, 2, 3, 4, 5, 6];
Alet count = nums.iter().filter(|x| *x % 2 == 0).count();
Blet count = nums.iter().filter(|&x| x % 2 == 0).count();
Clet count = nums.iter().filter(|x| *x % 2 == 1).count();
Dlet count = nums.iter().filter(|x| x % 2 == 0).count();
Attempts:
2 left
💡 Hint
Remember that iter() yields references, so you must dereference to get the value.

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

  1. Step 1: Understand the for loop over an array

    The for loop visits each element in the array named 'numbers'.
  2. Step 2: Action inside the loop

    Each element is printed on its own line using println! macro.
  3. Final Answer:

    Prints each number in the array on a new line -> Option B
  4. 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

  1. Step 1: Recall Rust for loop syntax

    Rust uses 'for variable in collection' to iterate over items.
  2. Step 2: Check each option

    for i in v { println!("{}", i); } matches correct syntax; others use invalid keywords.
  3. Final Answer:

    for i in v { println!("{}", i); } -> Option A
  4. 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

  1. Step 1: Understand iteration with references

    The loop uses '&num in &v' to borrow each element by reference and dereference it with '&num'.
  2. Step 2: Calculate sum of elements

    sum starts at 0, then adds 10, 20, and 30, resulting in 60.
  3. Final Answer:

    60 -> Option A
  4. 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

  1. Step 1: Check mutability of loop variable

    In Rust, loop variables are immutable by default; 'num' is a copy of array element.
  2. Step 2: Understand why 'num += 1' fails

    Trying to change 'num' causes error because it is not declared mutable.
  3. Final Answer:

    Cannot modify 'num' because it is an immutable copy -> Option D
  4. 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

  1. 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.
  2. Step 2: Collect results into a new vector

    collect() gathers the mapped lengths into a Vec<usize>.
  3. Final Answer:

    let lengths: Vec<usize> = words.iter().map(|w| w.len()).collect(); -> Option C
  4. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard