bhylu.com

Advertisements

Rust if, Booleans and match

Keep branches exhaustive and return the same type from each value branch.

How it works

if evaluates a Boolean condition, and it can also be an expression that returns a value. match compares a value against patterns and requires the possibilities to be covered. These constructs help make a small state decision explicit. A catch-all pattern should be a deliberate policy, not a way to conceal an unsupported state.

Run the code

Reviewed with Rust 1.97.0, edition 2024, using the standard library only. Save the complete download as lesson-name.rs in a separate learning folder, compile with rustc --edition=2024 lesson-name.rs and run the resulting program (lesson-name.exe on Windows). Use the actual lesson filename. The final project includes complete Cargo package files; run cargo test --offline and cargo run --offline from that separate package folder. There is no Rust browser runner; PHP, Apache and MySQL are not needed.

This complete example was executed in the stated local review environment.

Download complete source

Example

if-match.rs

fn main() {
    let count = 8;
    let status = if count > 0 { "available" } else { "empty" };
    let band = match count { 0 => "none", 1..=10 => "small", _ => "large" };
    assert_eq!(status, "available");
    assert_eq!(band, "small");
    println!("{status}; {band} batch");
}

Expected result

available; small batch

Both if branches produce string slices, so the binding has one consistent type. The match ranges cover zero, small positive counts and every remaining value of the inferred integer type. For real nonnegative quantities, choose an unsigned type and validation at the boundary rather than assuming negative states cannot arrive.

Primary technical reference: Rust documentation.