0
0
Rustprogramming~5 mins

If–else expression in Rust

Choose your learning style9 modes available
Introduction

If-else expressions help your program choose between two paths based on a condition. This lets your program make decisions like a person would.

When you want to check if a number is positive or negative and do something different for each.
When you want to decide what message to show based on a user's age.
When you want to set a value depending on whether a condition is true or false.
Syntax
Rust
let variable = if condition {
    value_if_true
} else {
    value_if_false
};
The if and else parts are expressions that return values.
You must include both if and else to assign a value to a variable.
Examples
This checks if number is greater than zero and prints if it is positive or not.
Rust
let number = 5;
let result = if number > 0 {
    "positive"
} else {
    "non-positive"
};
println!("{} is {}", number, result);
This sets can_vote to true if age is 18 or more, otherwise false.
Rust
let age = 18;
let can_vote = if age >= 18 { true } else { false };
println!("Can vote: {}", can_vote);
Sample Program

This program checks the temperature and prints if the weather is hot or cool.

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

Remember, if and else in Rust are expressions, so they return values.

Every if must have an else if you want to assign the result to a variable.

Summary

If-else expressions let your program choose between two options.

They return values, so you can store the result in a variable.

Always include else when assigning the result to a variable.