The 'match' Expression
Part of the Logic & Flow section of Coddy's Rust journey — lesson 1 of 66.
The match expression is Rust's powerful pattern matching tool that lets you compare a value against different patterns and execute code based on which pattern matches. Think of it as a more advanced version of if statements that can handle multiple conditions elegantly.
Here's the basic syntax of a match expression:
match value {
pattern1 => code_to_run,
pattern2 => code_to_run,
_ => default_code,
}Each line inside the match is called an "arm." The => separates the pattern from the code that runs when that pattern matches. The underscore _ is a special wildcard pattern that matches anything - it's like a "catch-all" for any value that doesn't match the other patterns.
Here's a simple example that checks a number:
let number = 2;
match number {
1 => println!("One"),
2 => println!("Two"),
_ => println!("Other"),
}In Rust, match expressions must be exhaustive, meaning they must handle every possible value. That's why the wildcard _ is so important - it ensures you've covered all cases that weren't explicitly matched.
Challenge
EasyWrite a function describe_number that takes num and returns a string description based on the number's value.
Use a match expression to return different descriptions for different numbers.
Conditions:
- If
numis0, return"zero" - If
numis1, return"one" - If
numis2, return"two" - If
numis3, return"three" - For any other number, return
"many"
Parameters:
num(i32): The number to describe
Returns: A string description of the number (String)
Cheat sheet
The match expression compares a value against different patterns and executes code based on which pattern matches:
match value {
pattern1 => code_to_run,
pattern2 => code_to_run,
_ => default_code,
}Each line inside the match is called an "arm." The => separates the pattern from the code that runs when that pattern matches.
Example:
let number = 2;
match number {
1 => println!("One"),
2 => println!("Two"),
_ => println!("Other"),
}The underscore _ is a wildcard pattern that matches anything not covered by other patterns. match expressions must be exhaustive - they must handle every possible value.
Try it yourself
fn describe_number(num: i32) -> String {
// Write code here
}
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 together