Making Decisions
Programs need to make choices all the time! Should the character jump or duck? Is the password correct? Is the player old enough? In Rust, we use if, else if, and else to make decisions.
Your First if
Notice something cool about Rust: no parentheses around the condition! In many other languages you'd write if (temperature > 30), but Rust keeps it clean. You do need the curly braces {} though — they're always required.
if and else
What if we want to do something when the condition is not true? That's what else is for:
Try changing age to 20 and run it again!
else if — Multiple Choices
Sometimes you need more than two options. Use else if to check additional conditions:
Rust checks each condition from top to bottom and runs the first one that's true. Once it finds a match, it skips the rest.
Comparison Operators
Here are all the ways to compare values in Rust:
| Operator | Meaning |
|---|---|
== | equal to |
!= | not equal to |
< | less than |
> | greater than |
<= | less than or equal to |
>= | greater than or equal to |
Watch out! A single = is for assigning values. A double == is for comparing. This is a super common mistake!
Boolean Operators — Combining Conditions
Sometimes you need to check more than one thing at once. Rust gives you three boolean operators:
| Operator | Meaning | Example |
|---|---|---|
&& | AND — both must be true | age >= 13 && age <= 19 |
|| | OR — at least one must be true | day == "Saturday" || day == "Sunday" |
! | NOT — flips true to false | !is_raining |
Conditions Must Be bool
Here's something important about Rust: conditions must be a boolean (true or false). Unlike some other languages, you can't use a number or string as a condition:
If you want to check whether a number is not zero, you need to be explicit: if count != 0.
Now let's practice making decisions with some exercises!