🚦 Control Flow: Conditional Expressions in Rust
The Traffic Light Story
Imagine you’re a little robot walking through a city. At every intersection, there’s a traffic light. The light tells you: “Should I go? Should I stop? Should I wait?”
That’s exactly what conditional expressions do in Rust! They help your program make decisions—just like you decide what to do at a traffic light.
🟢 What is an if Expression?
Think of if like asking a simple question:
“Is the light green?”
- Yes? → Walk!
- No? → Do nothing (or do something else)
Your First if Expression
let light = "green";
if light == "green" {
println!("Walk!");
}
What’s happening here?
- We have a light that’s
"green" - We ask: “Is the light green?”
- Yes! So we print “Walk!”
The Golden Rule 🌟
In Rust, the thing inside the if must be a true or false answer (a bool).
let age = 8;
if age >= 6 {
println!("You can go to school!");
}
The question: Is age 6 or more? → Yes (true) → Print the message!
🔴🟢 Adding else - The Other Choice
What if the light is NOT green? You need a backup plan!
else means: “If the first thing isn’t true, do THIS instead.”
let light = "red";
if light == "green" {
println!("Walk!");
} else {
println!("Stop and wait!");
}
Like a conversation:
“Is the light green?”
- No, it’s red. “Then stop and wait!”
Real Example: Is It Raining?
let raining = true;
if raining {
println!("Take an umbrella!");
} else {
println!("Enjoy the sunshine!");
}
🟡 The else if Chain - Multiple Choices
Sometimes you have MORE than two options. Like a traffic light with red, yellow, AND green!
let light = "yellow";
if light == "green" {
println!("Walk!");
} else if light == "yellow" {
println!("Hurry up!");
} else {
println!("Stop!");
}
How it works:
- Is it green? → No, skip.
- Is it yellow? → Yes! → “Hurry up!”
- We stop checking. Done!
The Ice Cream Shop Example 🍦
let scoops = 3;
if scoops == 1 {
println!("Small treat!");
} else if scoops == 2 {
println!("Medium delight!");
} else if scoops == 3 {
println!("Big happiness!");
} else {
println!("WOW! Ice cream mountain!");
}
🎁 The Magic Trick: if in let Statements
Here’s where Rust does something really cool!
In Rust, if is an expression. That means it can give you a value back—like a gift!
The Simple Version
let weather = "sunny";
let activity = if weather == "sunny" {
"Go to the park"
} else {
"Read a book"
};
println!("Today: {}", activity);
What’s happening?
- The
ifexpression figures out the answer - It gives that answer to
activity - No semicolons inside the
ifarms (that’s how Rust knows it’s a gift!)
⚠️ Important Rule: Same Type!
Both choices MUST give the same type of thing.
// ✅ GOOD - Both are strings
let snack = if hungry {
"apple"
} else {
"nothing"
};
// ❌ BAD - One is a number, one is text
// let result = if happy { 5 } else { "sad" };
Number Example
let score = 85;
let grade = if score >= 90 {
'A'
} else if score >= 80 {
'B'
} else if score >= 70 {
'C'
} else {
'D'
};
println!("Your grade: {}", grade);
🧩 Putting It All Together
Let’s build something fun! A robot that decides what to wear:
let temperature = 15;
let raining = true;
let outfit = if temperature > 25 {
"T-shirt and shorts"
} else if temperature > 15 {
"Light jacket"
} else {
"Warm coat"
};
let accessory = if raining {
"umbrella"
} else {
"sunglasses"
};
println!("Wear: {} with {}", outfit, accessory);
📊 Quick Decision Flow
graph TD A["Start: Check Condition"] --> B{Is it TRUE?} B -->|Yes| C["Do the IF block"] B -->|No| D{Any ELSE IF?} D -->|Yes| E{Is ELSE IF true?} E -->|Yes| F["Do ELSE IF block"] E -->|No| D D -->|No more| G{Is there ELSE?} G -->|Yes| H["Do ELSE block"] G -->|No| I["Skip everything"] C --> J["Done!"] F --> J H --> J I --> J
🌟 Key Takeaways
| Concept | What It Does | Example |
|---|---|---|
if |
Checks ONE condition | if sunny { go_outside() } |
else |
Backup plan | else { stay_home() } |
else if |
More options | else if cloudy { maybe_go() } |
if in let |
Returns a value | let x = if a { 1 } else { 2 }; |
🎯 Remember These Rules
- Condition must be
bool- true or false only! else ifchains - Check one by one, stop at first matchifas expression - Can return values (no semicolons inside!)- Same types - Both arms must return same type
🚀 You Did It!
You now understand how Rust makes decisions! Just like choosing what to do at a traffic light, your programs can now:
- ✅ Check if something is true
- ✅ Have backup plans with
else - ✅ Handle many options with
else if - ✅ Get values from decisions using
ifinlet
Next time you see a traffic light, remember: you’re thinking in Rust! 🦀
