If/Else and Match Statements

Rust supports standard if and else control flow like most programming languages.

If/Else Example

let number = 7;
if number < 5 {
    println!("Less than 5");
} else if number == 5 {
    println!("Equal to 5");
} else {
    println!("Greater than 5");
}

Rust does not require parentheses around conditions but uses curly braces for blocks.

Using if as an Expression

let condition = true;
let number = if condition { 5 } else { 6 };

All branches must return the same type.

Match Statement

match is a powerful control flow operator in Rust used for pattern matching:

let number = 1;
match number {
    1 => println!("One"),
    2 => println!("Two"),
    _ => println!("Something else"),
}

The _ acts like the default case.

← PrevNext →