Control Flow in Rust
by Hexagon, 2 min read rust guide
Control flow decides which code runs, and how many times. Rust has the usual suspects, if and loops, but with a twist: almost everything is an expression that gives back a value. Let's see what that means.
Conditions
Comparisons in Rust look like in most languages:
- Equal (==) and Not Equal (!=)
- Greater Than (>) and Less Than (<)
- Greater Than or Equal (>=) and Less Than or Equal (<=)
- Logical AND (&&), Logical OR (||) and Logical NOT (!)
There's no === in Rust, and you don't need it. Both sides of a comparison must
have the same type, so comparing the number 5 to the string "5" isn't
something that can go wrong at runtime. It's simply a compile error.
Rust also has no "truthy" or "falsy" values. A condition must be a bool:
You have to say what you mean, like if count != 0.
If Statements
Note that there are no parentheses around the condition, but the curly braces are always required, even for a single line.
If is an expression
In Rust, if gives back a value. That means you can use it on the right side of
a let:
This replaces the ternary operator (condition ? a : b) from JavaScript, which
Rust doesn't have. Both branches must give back the same type.
Match
match compares a value against a list of patterns, and runs the first one that
fits. Think of it as a switch statement, but more powerful:
The | combines several patterns, and _ matches anything, like default in a
switch. There's no break, and no falling through to the next case.
A match must cover every possible value. If you remove the _ line above, the
program won't compile, as there are many strings that aren't listed. This sounds
strict, but it's one of the best features of Rust, and we'll see why in the
article about enums.
match can also check ranges of numbers, and like if, it gives back a value:
90..=100 means 90 to 100, including 100.
Loops
Loop
loop runs forever, until you break out of it:
break can also give back a value from the loop:
While
while keeps going as long as a condition is true:
Note that Rust has no ++ operator. Use += 1 instead.
For
for loops over anything that can be iterated, like ranges and arrays:
There's no C-style for (let i = 0; i < 5; i++) loop in Rust. Ranges and
iterators cover the same needs, and you can't get the conditions wrong.
continue skips to the next round of a loop, just like in JavaScript.
Loop labels
When you have loops inside loops, you can give a loop a name, and break out of
that one directly:
A Call to Action
Play around with the examples, tweak the conditions, and watch the results. Here is an example covering what we've learned so far:
You might notice that the match appears twice, using exactly the same code. In
the next lesson, we'll fix that with functions.