All lessons

Making Decisions

8 min · Rust

Run different code depending on whether something is true.

Rust · Making Decisions0/5 cleared

Enemy 1 of 5

Every real program needs to make choices: send this email only if the form is valid, show a discount only if the cart is over $50, and so on. In Rust, that decision-making is built with if. An if statement checks a condition — an expression that evaluates to true or false — and runs the code inside its { } block only when that condition is true.

You can pair if with else to provide a fallback: if the condition is false, the code inside else runs instead. Exactly one of the two blocks executes, never both and never neither.

Notice that Rust's if doesn't need parentheses around the condition, unlike C, Java, or JavaScript — you write if temperature > 20 { ... }, not if (temperature > 20) { ... } (parentheses are allowed but not required, and idiomatic Rust code omits them). The curly braces, on the other hand, are mandatory even for a single-line block — Rust never allows a bare unbraced statement after if the way C does, which eliminates a classic class of bugs where an unindented line quietly falls outside the intended block.

You
Memory-Leak Rat

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: Cold