The 'if let' Expression
Part of the Logic & Flow section of Coddy's Rust journey — lesson 4 of 66.
Sometimes you only need to check for one specific pattern and don't care about all the other possibilities. Writing a full match expression with just one meaningful arm and a catch-all _ can feel verbose. Rust provides if let as a more concise alternative for these situations.
The if let expression lets you combine pattern matching with conditional logic in a single, readable statement. Here's the basic syntax:
if let pattern = value {
// code to run if pattern matches
}For example, instead of writing a match with only one useful arm:
let number = 5;
match number {
5 => println!("Found five!"),
_ => (), // do nothing for other values
}You can use if let to make it cleaner:
let number = 5;
if let 5 = number {
println!("Found five!");
}The if let expression only executes the code block when the pattern matches. If it doesn't match, nothing happens - there's no need for an explicit "else" case unless you want one.
Challenge
EasyYou will receive a number as input. Read the input, convert it to an integer, and use an if let expression to check if the number is exactly 42. If it matches, print "The answer!". If it doesn't match, print nothing.
Requirements:
- Use an
if letexpression to check if the number equals42 - If the number is
42, print"The answer!" - If the number is anything else, do not print anything
Input: A single integer
Output: Print "The answer!" if the number is 42, otherwise print nothing
Cheat sheet
The if let expression provides a concise way to match a single pattern without writing a full match statement.
Basic syntax:
if let pattern = value {
// code to run if pattern matches
}Example comparing match and if let:
// Using match
let number = 5;
match number {
5 => println!("Found five!"),
_ => (), // do nothing for other values
}
// Using if let (more concise)
let number = 5;
if let 5 = number {
println!("Found five!");
}The if let expression only executes when the pattern matches. If it doesn't match, nothing happens unless you add an explicit else clause.
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 number: i32 = input.trim().parse().expect("Please enter a valid number");
// TODO: Write your code below
// Use if let to check if number equals 42
}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