Conditional Expressions

Loading concept...

🚦 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?

  1. We have a light that’s "green"
  2. We ask: “Is the light green?”
  3. 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:

  1. Is it green? → No, skip.
  2. Is it yellow? → Yes! → “Hurry up!”
  3. 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 if expression figures out the answer
  • It gives that answer to activity
  • No semicolons inside the if arms (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

  1. Condition must be bool - true or false only!
  2. else if chains - Check one by one, stop at first match
  3. if as expression - Can return values (no semicolons inside!)
  4. 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 if in let

Next time you see a traffic light, remember: you’re thinking in Rust! 🦀

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive - Premium Content

Please sign in to view this interactive content and start learning.

Upgrade to Premium to unlock full access to all interactive content.

Stay Tuned!

Interactive content is coming soon.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Cheatsheet - Premium Content

Please sign in to view this cheatsheet and start learning.

Upgrade to Premium to unlock full access to all cheatsheets.

Stay Tuned!

Cheatsheet is coming soon.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Quiz - Premium Content

Please sign in to view this quiz and test your knowledge.

Upgrade to Premium to unlock full access to all quizzes.

Stay Tuned!

Quiz is coming soon.

Flashcard Preview

Flashcard - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Flashcard - Premium Content

Please sign in to view flashcards and reinforce your learning.

Upgrade to Premium to unlock full access to all flashcards.

Stay Tuned!

Flashcards are coming soon.