📖 Scenario: Imagine you are building a simple program that stores a user's favorite number. Sometimes the user has a favorite number, and sometimes they don't. We will use Rust's Option enum to handle this situation safely.
🎯 Goal: Build a Rust program that uses the Option enum to store a favorite number, check if it exists, and print it or a message if it is missing.
📋 What You'll Learn
Create a variable called favorite_number that can hold an Option<i32> value.
Create a variable called default_number with the value 10.
Use a match expression on favorite_number to get the number or use default_number if None.
Print the final number with a message.
💡 Why This Matters
🌍 Real World
Handling optional values safely is common in real-world programs, such as user input, configuration settings, or data that may be missing.
💼 Career
Understanding <code>Option</code> is essential for Rust developers to write safe and bug-free code that avoids crashes from missing values.
Progress0 / 4 steps
1
DATA SETUP: Create an Option variable
Create a variable called favorite_number and set it to Some(7) using Rust's Option<i32> enum.
Rust
Hint
Use let favorite_number: Option = Some(7); to create the variable.
2
CONFIGURATION: Create a default number variable
Add a variable called default_number and set it to 10.
Rust
Hint
Use let default_number = 10; to create the variable.
3
CORE LOGIC: Use match to get the number or default
Use a match expression on favorite_number to create a variable called number. If Some(value), use value. If None, use default_number.
Rust
Hint
Use match favorite_number with arms Some(value) => value and None => default_number.
4
OUTPUT: Print the final number
Print the message "The number is: {number}" using println!.
Rust
Hint
Use println!("The number is: {}", number); to print the result.
Practice
(1/5)
1. What does the Option enum represent in Rust?
easy
A. A way to handle errors explicitly.
B. A value that can be either something (Some) or nothing (None).
C. A type of loop in Rust.
D. A macro for printing output.
Solution
Step 1: Understand the purpose of Option enum
The Option enum is used to represent a value that might be present or absent.
Step 2: Match the description to the correct option
A value that can be either something (Some) or nothing (None). correctly describes Option as either Some(value) or None, representing presence or absence.
Final Answer:
A value that can be either something (Some) or nothing (None). -> Option B
Quick Check:
Option enum = Some or None [OK]
Hint: Option means value or no value, like a yes/no box [OK]
Common Mistakes:
Confusing Option with error handling Result type
Thinking Option is a loop or macro
Assuming Option always contains a value
2. Which of the following is the correct way to create an Option containing the integer 5?
easy
A. let x = Some(5);
B. let x = Option(5);
C. let x = Some[5];
D. let x = Option::new(5);
Solution
Step 1: Recall the syntax for creating an Option with a value
In Rust, Some(value) wraps a value inside an Option.
Step 2: Identify the correct syntax among options
let x = Some(5); uses Some(5), which is the correct syntax. Others are invalid or do not exist.
Final Answer:
let x = Some(5); -> Option A
Quick Check:
Use Some(value) to create Option with value [OK]
Hint: Use Some(value) to wrap a value in Option [OK]
Common Mistakes:
Using Option(5) instead of Some(5)
Using square brackets instead of parentheses
Trying to call Option::new which doesn't exist
3. What will be the output of this Rust code?
let x: Option<i32> = Some(10);
match x {
Some(val) if val > 5 => println!("Greater than 5: {}", val),
Some(val) => println!("Value: {}", val),
None => println!("No value"),
}
medium
A. Value: 10
B. No value
C. Greater than 5: 10
D. Compilation error
Solution
Step 1: Analyze the Option value and match arms
The variable x is Some(10). The match checks if val > 5 first.
Step 2: Determine which match arm runs
Since 10 > 5, the first arm runs, printing "Greater than 5: 10".
Final Answer:
Greater than 5: 10 -> Option C
Quick Check:
Some(10) with val > 5 prints "Greater than 5: 10" [OK]
Hint: Match with if guards runs first matching condition [OK]
Common Mistakes:
Ignoring the if guard and picking second arm
Thinking None arm runs for Some value
Assuming compilation error due to if guard
4. Identify the error in this Rust code snippet using Option:
let x: Option<i32> = None;
let y = x.unwrap();
println!("Value: {}", y);
medium
A. No error, prints "Value: None"
B. unwrap returns Option, not value
C. Compilation error due to type mismatch
D. Runtime panic because unwrap on None
Solution
Step 1: Understand unwrap behavior on None
Calling unwrap() on None causes a runtime panic because there is no value.
Step 2: Check the code behavior
Since x is None, unwrap() panics and program crashes at runtime.
Final Answer:
Runtime panic because unwrap on None -> Option D
Quick Check:
unwrap on None panics at runtime [OK]
Hint: unwrap on None causes panic, avoid without check [OK]
Common Mistakes:
Thinking unwrap returns None safely
Expecting compilation error instead of runtime panic
Assuming unwrap returns Option instead of value
5. Given a vector of integers, how can you use Option to safely find the first even number and print it, or print "No even number" if none exist?
Choose the correct Rust code snippet.
hard
A. let nums = vec![1, 3, 5];
if let Some(even) = nums.iter().find(|&&x| x % 2 == 0) {
println!("First even: {}", even);
} else {
println!("No even number");
}
B. let nums = vec![1, 3, 5];
let even = nums.iter().find(|x| x % 2 == 0).unwrap();
println!("First even: {}", even);
C. let nums = vec![1, 3, 5];
let even = nums.iter().filter(|x| x % 2 == 0).next().unwrap();
println!("First even: {}", even);
D. let nums = vec![1, 3, 5];
let even = nums.iter().find(|&&x| x % 2 == 0).unwrap_or(0);
println!("First even: {}", even);
Solution
Step 1: Understand safe Option handling with find()
nums.iter().find returns Option<&i32>. Using if let Some(even) safely handles Some or None.
Step 2: Check each option for correctness and safety
let nums = vec![1, 3, 5];
if let Some(even) = nums.iter().find(|&&x| x % 2 == 0) {
println!("First even: {}", even);
} else {
println!("No even number");
} uses if let to print the even number or fallback message safely. Others use unwrap() which panics if no even number.
Final Answer:
Option A code safely finds and prints first even or fallback message. -> Option A
Quick Check:
Use if let Some(...) to safely handle Option from find() [OK]
Hint: Use if let Some(...) to safely unwrap Option without panic [OK]
Common Mistakes:
Using unwrap() without checking for None causes panic
Incorrect closure syntax in find/filter
Using unwrap_or with incompatible types
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.