0
0
Rustprogramming~5 mins

If expression in Rust

Choose your learning style9 modes available
Introduction

An if expression lets your program choose what to do based on a condition. It helps your code make decisions like a fork in the road.

When you want to check if a number is positive or negative and act differently.
When you want to decide what message to show based on user input.
When you want to run some code only if a certain condition is true.
When you want to assign a value based on a condition.
When you want to handle different cases without repeating code.
Syntax
Rust
if condition {
    // code if condition is true
} else {
    // code if condition is false
}

The condition must be a boolean (true or false).

In Rust, if is an expression, so it returns a value.

Examples
Runs the code only if x is greater than zero.
Rust
if x > 0 {
    println!("x is positive");
}
Checks if x is even or odd and prints a message.
Rust
if x % 2 == 0 {
    println!("x is even");
} else {
    println!("x is odd");
}
Uses if as an expression to assign a value to sign.
Rust
let sign = if x < 0 { "negative" } else { "non-negative" };
Sample Program

This program checks if x is positive, negative, or zero and prints a message. Then it uses an if expression to find if x is even or odd and prints that.

Rust
fn main() {
    let x = 7;
    if x > 0 {
        println!("{} is positive", x);
    } else if x < 0 {
        println!("{} is negative", x);
    } else {
        println!("{} is zero", x);
    }

    let description = if x % 2 == 0 { "even" } else { "odd" };
    println!("{} is {}", x, description);
}
OutputSuccess
Important Notes

Remember, the condition must always be a boolean; Rust does not allow numbers or other types as conditions.

You can chain multiple else if blocks to check many conditions.

Because if is an expression, you can assign its result directly to a variable.

Summary

If expressions let your program choose what to do based on true or false conditions.

You can use if with else and else if to handle multiple cases.

In Rust, if returns a value, so you can assign it to variables.