0
0
Rustprogramming~5 mins

Using if as expression in Rust

Choose your learning style9 modes available
Introduction

Using if as an expression lets you choose a value based on a condition in one simple step.

When you want to set a variable to one value or another depending on a condition.
When you want to return different results from a function based on a condition.
When you want to write shorter code without repeating variable names.
When you want to decide a value inside a larger expression.
Syntax
Rust
let variable = if condition {
    value_if_true
} else {
    value_if_false
};

The if block returns a value, so you can assign it directly.

Both branches must return the same type of value.

Examples
This sets result to "positive" because number is 5.
Rust
let number = 5;
let result = if number > 0 { "positive" } else { "non-positive" };
This sets can_vote to true because age is 18 or more.
Rust
let age = 18;
let can_vote = if age >= 18 { true } else { false };
This chooses a letter grade based on the score using multiple if expressions.
Rust
let score = 75;
let grade = if score >= 90 {
    'A'
} else if score >= 80 {
    'B'
} else {
    'C'
};
Sample Program

This program checks the temperature and sets weather to "hot" or "cool" using if as an expression, then prints the result.

Rust
fn main() {
    let temperature = 30;
    let weather = if temperature > 25 {
        "hot"
    } else {
        "cool"
    };
    println!("The weather is {}.", weather);
}
OutputSuccess
Important Notes

Remember to end the if expression with a semicolon if you assign it to a variable.

All branches must return the same type, or Rust will give an error.

Summary

if can be used to pick a value based on a condition.

This helps write shorter and clearer code.

Make sure all branches return the same type.