Using 'match' with 'Option'
Part of the Logic & Flow section of Coddy's Rust journey — lesson 36 of 66.
Now that you understand what Option is, let's learn the most common and explicit way to handle it: using a match expression. This approach forces you to consider both possible cases - when there's a value and when there isn't.
The match expression works perfectly with Option because you can create arms for both variants:
let maybe_name = Some("Alice".to_string());
match maybe_name {
Some(name) => println!("Hello, {}!", name),
None => println!("Hello, stranger!"),
}Notice how the Some(name) arm extracts the value from inside the Some variant. The variable name now contains the actual String, not the Option. This is called destructuring - you're pulling the inner value out of the wrapper.
The None arm handles the case where there's no value, allowing you to provide alternative behavior like showing a default message or taking a different action entirely.
Challenge
EasyYou will receive a student name as input. The name might be present in the system or it might be missing. Create an Option<String> that contains Some(name) if the name is not empty, or None if the name is empty. Use a match expression to handle both cases and print the appropriate message.
Requirements:
- Read the input as a string (student name)
- Trim any whitespace from the input using
.trim() - Create an
Option<String>variable:- If the trimmed name is not empty, assign
Some(name.to_string()) - If the trimmed name is empty, assign
None
- If the trimmed name is not empty, assign
- Use a
matchexpression to handle both variants of theOption - In the
Some(name)arm, print:Welcome, [name]! - In the
Nonearm, print:No name provided
Input:
- A single line containing either a student name or an empty line
Output:
- If a name is provided:
Welcome, [name]! - If no name is provided (empty input):
No name provided
Cheat sheet
Use a match expression to handle Option values by creating arms for both variants:
let maybe_name = Some("Alice".to_string());
match maybe_name {
Some(name) => println!("Hello, {}!", name),
None => println!("Hello, stranger!"),
}The Some(name) arm uses destructuring to extract the inner value from the Some variant. The variable name contains the actual value, not the Option wrapper.
The None arm handles the case where there's no value, allowing you to provide alternative behavior.
Try it yourself
use std::io;
fn main() {
// Read input
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Failed to read line");
let name = input.trim();
// TODO: Create an Option<String> based on whether the name is empty or not
// TODO: Use a match expression to handle Some and None cases and print the appropriate message
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Control Flow
The 'match' ExpressionMatching Multiple ValuesMatching RangesThe 'if let' ExpressionLoops as ExpressionsRecap - Simple Command Parser4Grouping Data with Structs
What is a Struct?Structs OverviewAccessing Struct FieldsMutable StructsStructs as Function ParametersTuple StructsRecap - Create a Book Struct7Handling Errors with 'Result'
What is a 'Result'?Using 'match' with 'Result'is_ok() and is_err()Shortcuts: unwrap and expectThe Question Mark Operator '?'Parsing Strings to NumbersRecap - Safe Division Function10Closures & Anonymous Functions
What is a Closure?Defining a Simple ClosureClosures with ParametersCapturing the EnvironmentRecap - Simple Adder Closure2Introduction to Vectors
What is a Vector?Creating a VectorAdding Elements with pushAccessing Vector ElementsIterating Over a VectorMutable IterationRemoving ElementsRecap - Basic Score Tracker5Key-Value Pairs with Hash Maps
What is a Hash Map?Creating a Hash MapInserting Key-Value PairsAccessing ValuesIterating Over a Hash MapUpdating a ValueRemoving a PairRecap - Word Counter8Project: Simple Item Inventory
Project SetupAdding an ItemChecking StockSelling an ItemPutting it all together6Handling Absence with 'Option'
What is an 'Option'?Using 'match' with 'Option'is_some() and is_none()Unwrapping an 'Option'The expectProviding a Default: unwrap_orRecap - Find an Element