0
0
Rustprogramming~3 mins

Why Using if as expression in Rust? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could pick values with a simple, elegant one-liner instead of clunky multi-line code?

The Scenario

Imagine you want to pick a value based on a condition, like choosing between two numbers. Without using if as an expression, you have to write extra lines to declare a variable first, then assign it inside the if block.

The Problem

This manual way is slow and clunky because you write more code than needed. It's easy to make mistakes by forgetting to assign the variable or mixing up the logic. It also makes your code longer and harder to read.

The Solution

Using if as an expression lets you directly get a value from the if condition. This means you can write cleaner, shorter code that is easier to understand and less error-prone.

Before vs After
Before
let mut x;
if condition {
    x = 5;
} else {
    x = 10;
}
After
let x = if condition { 5 } else { 10 };
What It Enables

This lets you write neat, concise code that picks values on the spot, making your programs simpler and clearer.

Real Life Example

Think about deciding the price of a ticket: if someone is a child, the price is lower; otherwise, it's full price. Using if as an expression lets you set the price in one simple line.

Key Takeaways

Manual value assignment with if is longer and error-prone.

If as expression returns values directly, simplifying code.

It makes your programs easier to read and maintain.