Expressions & Flow · 13 min · free with an account

Control Flow

Lesson preview · about 30%

Expressions and loops model decisions without hidden coercion.

Core idea

if is an expression; every branch must produce the same type.

Start with the idea

Because if is an expression, both branches must produce the same type — there is no silent conversion to paper over a mismatch. loop, while, and for then express three different repetition rules: forever, until a condition fails, and over an iterator.

In the example, value % 2 == 0 evaluates to bool. Both if branches produce a &str, so the entire if expression can initialize label. If one branch returned a number instead, rustc would reject the assignment because a single expression cannot have two unrelated result types. This is a useful discipline: deciding what label means happens in one place, and the loop can simply print it.

The range 0..3 supplies 0, 1, and 2 to for. Each iteration binds index to the next value and prints one line. The loop does not need a separate counter mutation or a manual exit condition.

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