Menu
Coddy logo textTech

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 icon

Challenge

Easy

You 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 let expression to check if the number equals 42
  • 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
    
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow