What if you could pick values with a simple, elegant one-liner instead of clunky multi-line code?
Why Using if as expression in Rust? - Purpose & Use Cases
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.
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.
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.
let mut x; if condition { x = 5; } else { x = 10; }
let x = if condition { 5 } else { 10 };
This lets you write neat, concise code that picks values on the spot, making your programs simpler and clearer.
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.
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.