# Expressions and Pattern Matching — Rust

Source: https://www.skillbyai.com/en/rust/b-expr

> if, loop and match return values.

## Everything is an expression

In Rust, `if`, `match` and blocks are **expressions** that produce values, so you can write `let feel = if t > 30 { "hot" } else { "pleasant" };`. `loop` can return a value with `break value`. `match` compares a value against **patterns** (literals, ranges, enum variants, tuples, guards) and must be **exhaustive**: every possible value has to be handled, which the compiler checks. Statements end with a semicolon; the last expression in a block without one is its value.

## if as a value, match on ranges, loop with break value, run

I ran this with Rust 1.99.0 (cargo run, edition 2024, standard library only). match covers all i32 values with ranges and a wildcard; loop returns 30 through break.

```rust
fn classify(n: i32) -> &'static str {
    match n {
        i32::MIN..=-1 => "negative",
        0 => "zero",
        1..=9 => "small",
        _ => "large",
    }
}

fn main() {
    let temp = 31;
    let feel = if temp > 30 { "hot" } else { "pleasant" }; // if is an expression
    println!("{feel}");
    for n in [-5, 0, 7, 42] {
        print!("{} ", classify(n));
    }
    println!();
    let mut attempts = 0;
    let result = loop {
        attempts += 1;
        if attempts == 3 {
            break attempts * 10; // loop can return a value
        }
    };
    println!("result={result}");
}
```

Output:

```
hot
negative zero small large 
result=30
```

## Let the compiler check exhaustiveness

Avoid a catch-all _ when matching your own enums, so adding a variant produces errors wherever handling is missing.

**Quiz:** What happens if a match does not cover every possible value?

- [ ] It returns null
- [x] The code does not compile
- [ ] It panics at runtime only
- [ ] The last arm is used automatically

*Answer:* The code does not compile. Matches must be exhaustive.
