Exerpad
🔥1
10 XP
Lv.1 Beginner
Log In

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

rust
fn main() {
let temperature = 35;

if temperature > 30 {
println!("It's hot outside! 🔥");
}
}

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:

rust
fn main() {
let age = 15;

if age >= 18 {
println!("You can vote!");
} else {
println!("Too young to vote.");
}
}

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
fn main() {
let score = 85;

if score >= 90 {
println!("Grade: A");
} else if score >= 80 {
println!("Grade: B");
} else if score >= 70 {
println!("Grade: C");
} else {
println!("Keep practicing!");
}
}

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:

OperatorMeaning
==equal to
!=not equal to
<less than
>greater than
<=less than or equal to
>=greater than or equal to
rust
fn main() {
let lives = 0;

if lives == 0 {
println!("Game Over!");
} else {
println!("Keep playing!");
}
}

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:

OperatorMeaningExample
&&AND — both must be trueage >= 13 && age <= 19
||OR — at least one must be trueday == "Saturday" || day == "Sunday"
!NOT — flips true to false!is_raining
rust
fn main() {
let age = 15;
let has_ticket = true;

if age >= 12 && has_ticket {
println!("Welcome to the movie! 🎬");
} else {
println!("Sorry, you can't enter.");
}
}

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:

rust
fn main() {
let has_key = true;

// ✅ This works — has_key is a bool
if has_key {
println!("Door unlocked!");
}

// ❌ This would NOT work in Rust:
// let count = 5;
// if count { } // Error! count is a number, not a bool
}

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!