Rs
Module 1Functions & Control FlowLesson 8 of 1018 min

if / else as Expressions

Branching with equal types in both arms — classify trades, regimes, and signs.

if is an expression

rust
let side = if qty > 0.0 {
    "long"
} else if qty < 0.0 {
    "short"
} else {
    "flat"
};

Both (all) branches must produce the same type.

Blocks yield values

rust
let fee_bps = if notional > 1_000_000.0 { 0.5 } else { 1.0 };

No truthy/falsey junk

Only bool works in conditions — not numbers or Options.

Example: trading session

rust
fn session_label(hour_utc: u32) -> &'static str {
    if hour_utc < 13 {
        "ASIA"
    } else if hour_utc < 21 {
        "LONDON_NY_OVERLAP_OR_EU"
    } else {
        "US"
    }
}

Exercise

Classify a return into UP / DOWN / FLAT with a threshold.

Challenge

Return a tuple (label, severity) where severity is LOW/HIGH if |ret| > 2*threshold.

Tips
  • Branches must match types
  • Use .abs() for magnitude checks
  • &'static str is a string literal type — fine for labels

Try it live

if / else as ExpressionsRust 2021
Loading editor…
Output
Press Run to compile and execute.