Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Rust Dictionary

  1. Home
  2. Rust Dictionary
  3. if / else / if let

if / else / if let

In Rust, if is an expression and can return a value. if let is a concise syntax for pattern matching on Option or Result values.

Syntax

// Standard if/else
if condition {
    // body
} else if condition2 {
    // body
} else {
    // body
}

// Used as an expression (returns a value)
let variable = if condition { value1 } else { value2 };

// if let (pattern-match branching)
if let pattern = value {
    // runs when pattern matches
} else {
    // runs when pattern does not match
}

if / if let Comparison

SyntaxDescription
if conditionStandard conditional branch that evaluates a bool value.
else if conditionChains multiple conditions together.
let x = if ... { } else { }Uses if as an expression to assign a value to a variable. Each branch must return the same type.
if let Some(x) = optRuns only when the Option is Some. More concise than match for a single pattern.
if let Ok(x) = resultRuns only when the Result is Ok.

Sample Code

fn classify(n: i32) -> &'static str {
    if n > 0 {
        "positive"
    } else if n < 0 {
        "negative"
    } else {
        "zero"
    }
}

fn main() {
    // Basic if/else
    let score = 75;
    let grade = if score >= 80 {
        "A"
    } else if score >= 60 {
        "B"
    } else {
        "C"
    };
    println!("Grade: {}", grade); // Prints "B"

    // Handle an Option with if let
    let some_value: Option<i32> = Some(42);
    if let Some(v) = some_value {
        println!("Value is {}", v); // Prints "42"
    } else {
        println!("No value");
    }

    // Handle a Result with if let
    let result: Result<i32, &str> = Ok(100);
    if let Ok(n) = result {
        println!("Success: {}", n);
    }

    println!("{}", classify(5));
    println!("{}", classify(-3));
}

Notes

Because if in Rust is an expression rather than a statement, you can use it in place of a ternary operator. Each branch must return the same type; a type mismatch causes a compile error.

if let is useful when you only need to handle a single pattern from an Option or Result. When you need to handle multiple patterns, match is clearer and more readable. See match / Pattern Matching for details.

If you find any errors or copyright issues, please .