Challenge - 5 Problems
Rust Iteration Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput 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);
}Attempts:
2 left
💡 Hint
Remember that iterating with &mut allows modifying elements in place.
✗ Incorrect
The for loop iterates over mutable references to each element, adding 2 to each. So the vector changes from [1,2,3,4] to [3,4,5,6].
❓ Predict Output
intermediateOutput 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); }
Attempts:
2 left
💡 Hint
Sum all values in the map by iterating over references.
✗ Incorrect
The values 1, 2, and 3 are summed to 6. Iterating over &map yields (&key, &value) pairs.
🔧 Debug
advancedWhy 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);
}
}Attempts:
2 left
💡 Hint
Think about Rust's borrowing rules when iterating and modifying the same collection.
✗ Incorrect
The iterator borrows `v` immutably, but the loop tries to mutate `v` by pushing elements, causing a conflict.
📝 Syntax
advancedWhich 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];
Attempts:
2 left
💡 Hint
Remember that iter() returns references, so you may need to dereference.
✗ Incorrect
Option C correctly uses iter() and dereferences the reference to print the value. Option C moves the vector, B prints references, C requires mutable vector.
🚀 Application
expertCount 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];
Attempts:
2 left
💡 Hint
Remember that iter() yields references, so you must dereference to get the value.
✗ Incorrect
Option A correctly dereferences `x` to get the integer and filters even numbers. Option A has wrong closure argument pattern, C tries to use reference as integer, D counts odd numbers.
