Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ EXPRESS THE WORK
BUILD NOTE 06 / 53

Choose a path on purpose.

Use expressions and short-circuit evaluation to encode decisions.

BY NAVAN SAMI◷ 7 MIN READFOUNDATIONSRUST 2024

01 Understand the contract

An if condition must be a bool; numbers do not convert to truthiness automatically. An if/else can produce a value, provided both branches have compatible types. Logical && and || short-circuit, so the second operand is evaluated only when needed. This lets a guard protect an operation such as division. State conditions in terms of your domain rather than clever punctuation, and test the boundary where the decision changes.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/conditions/src/main.rs
fn main() {
    let age = 19;
    let status = if age >= 18 { "adult" } else { "minor" };
    let denominator = 0;
    let safe = denominator != 0 && 10 / denominator > 1;
    println!("{status}, safe={safe}");
}
↳ EXPECTED OUTPUT
adult, safe=false
  1. 1

    The two status branches both return string slices.

  2. 2

    The false first operand prevents division by zero.

  3. 3

    Test age 17 and 18 to exercise the boundary.

From the extracted rust-workbench folder
cargo run -p lesson_conditions

03 Mind the boundary

04 Your next build

A SMALL MISSION

Classify temperatures below 0 as freezing, from 0 to 29 as mild, and 30 or above as hot.

Reveal one possible solution +
solutions/conditions/src/main.rs
fn weather(t: i32) -> &'static str {
    if t < 0 {
        "freezing"
    } else if t < 30 {
        "mild"
    } else {
        "hot"
    }
}
fn main() {
    assert_eq!(weather(-1), "freezing");
    assert_eq!(weather(0), "mild");
    assert_eq!(weather(30), "hot");
}

05 Check your reasoning

QUICK SIGNAL CHECK

Does if 1 compile as a condition?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.