Challenge - 5 Problems
Option Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output of this Rust code using Option?
Consider the following Rust code snippet. What will it print?
Rust
fn main() {
let x: Option<i32> = Some(10);
let y: Option<i32> = None;
println!("{}", x.unwrap_or(5) + y.unwrap_or(3));
}Attempts:
2 left
💡 Hint
Remember unwrap_or returns the value inside Some or the default if None.
✗ Incorrect
x.unwrap_or(5) returns 10 because x is Some(10). y.unwrap_or(3) returns 3 because y is None. Their sum is 13.
❓ Predict Output
intermediateWhat does this Rust code print when matching Option?
Look at this Rust code using match with Option. What is printed?
Rust
fn main() {
let val = Some("hello");
match val {
Some(s) if s.len() > 3 => println!("Long: {}", s),
Some(s) => println!("Short: {}", s),
None => println!("No value"),
}
}Attempts:
2 left
💡 Hint
Check the length of the string inside Some and the if guard.
✗ Incorrect
The string "hello" has length 5, which is greater than 3, so the first arm matches and prints "Long: hello".
🔧 Debug
advancedWhat error does this Rust code produce?
This Rust code tries to unwrap an Option. What error will it cause when run?
Rust
fn main() {
let val: Option<i32> = None;
println!("{}", val.unwrap());
}Attempts:
2 left
💡 Hint
unwrap on None causes a runtime panic, not a compile error.
✗ Incorrect
Calling unwrap on None causes a panic at runtime with the message 'called `Option::unwrap()` on a `None` value'.
🧠 Conceptual
advancedHow many items are in the resulting vector after filtering Options?
Given this Rust code, how many elements does the vector 'numbers' contain after filtering?
Rust
fn main() {
let values = vec![Some(1), None, Some(3), Some(5), None];
let numbers: Vec<i32> = values.into_iter().filter_map(|x| x).collect();
println!("{}", numbers.len());
}Attempts:
2 left
💡 Hint
filter_map removes None and unwraps Some values.
✗ Incorrect
There are three Some values in the vector, so after filtering, numbers has length 3.
❓ Predict Output
expertWhat is the output of this nested Option handling code?
Analyze this Rust code with nested Options and unwrap_or_else. What does it print?
Rust
fn main() {
let a: Option<Option<i32>> = Some(None);
let result = a.unwrap_or_else(|| Some(10)).unwrap_or(20);
println!("{}", result);
}Attempts:
2 left
💡 Hint
unwrap_or_else returns the inner Option or default; then unwrap_or unwraps inner Option or default.
✗ Incorrect
a is Some(None), so unwrap_or_else returns None (the inner Option). Then unwrap_or(20) returns 20 because inner Option is None.
