0
0
Rustprogramming~3 mins

Why If expression in Rust? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a simple 'if expression' can turn messy checks into clean, powerful code!

The Scenario

Imagine you want to decide what to wear based on the weather. You check the temperature and then write separate code for each case, repeating yourself a lot.

The Problem

Writing many separate checks and repeating code makes your program long, confusing, and easy to mess up. Changing one condition means hunting through many places to fix it.

The Solution

The if expression lets you check a condition and immediately get a result from it. This keeps your code short, clear, and easy to change.

Before vs After
Before
let temp = 30;
let outfit;
if temp > 20 {
    outfit = "T-shirt";
} else {
    outfit = "Jacket";
}
After
let temp = 30;
let outfit = if temp > 20 { "T-shirt" } else { "Jacket" };
What It Enables

You can write simple, neat code that chooses values based on conditions without extra steps or confusion.

Real Life Example

Choosing a discount rate in a shopping app based on how much a customer spends, all in one clear line of code.

Key Takeaways

If expressions combine condition checks and results in one place.

They reduce repeated code and make programs easier to read.

They help you write smarter decisions in your code simply.