Rust Foundations · 10 min · free with an account

Booleans

Lesson preview · about 30%

A comparison produces a bool, and a branch requires one. && and || can skip their right-hand expression as soon as the result is known.

Core idea

if requires bool; Rust has no implicit numeric truthiness.

Start with the idea

A condition is not an arbitrary number or string in Rust. Comparisons such as builds > 0 and errors == 0 each produce a bool. The example combines them into ready, a name that expresses the decision the program needs to make. That makes the if branch easy to inspect: it runs only after at least one build exists and no errors remain. If your code says if count, rustc asks for a real boolean condition instead of guessing whether zero should mean false.

The logical operators also control which work is performed. For left && right, a false left side settles the answer, so right is not evaluated. For left || right, a true left side settles it. This is short-circuiting, shown in the diagram by the crossed-out right branch. It matters when the right expression is expensive or valid only after the left has checked a precondition. Do not use side effects on the right merely because you expect them to run: the operator may skip them.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Rust Basics