0
0
Rustprogramming~5 mins

Nested conditions in Rust

Choose your learning style9 modes available
Introduction

Nested conditions let you check one condition inside another. This helps you make decisions step-by-step, like asking multiple questions in order.

When you want to check if a number is positive and also if it is even.
When you need to decide what to do based on multiple levels of choices, like checking age and then checking if a ticket is valid.
When you want to handle special cases inside a general case, like checking if a user is logged in and then if they have admin rights.
Syntax
Rust
if condition1 {
    if condition2 {
        // code if both conditions are true
    } else {
        // code if condition1 is true but condition2 is false
    }
} else {
    // code if condition1 is false
}

You can put one if inside another to check multiple things.

Use else to handle cases when conditions are not met.

Examples
This checks if a number is positive, then inside that, checks if it is even.
Rust
let number = 10;
if number > 0 {
    if number % 2 == 0 {
        println!("Number is positive and even");
    }
}
This checks age in two steps: first if adult, then if allowed to drink.
Rust
let age = 20;
if age >= 18 {
    if age < 21 {
        println!("Adult but not allowed to drink alcohol in some countries");
    } else {
        println!("Adult and allowed to drink alcohol");
    }
} else {
    println!("Not an adult");
}
Sample Program

This program checks the temperature in steps: first if above freezing, then if warm or just cold.

Rust
fn main() {
    let temperature = 30;
    if temperature > 0 {
        if temperature > 25 {
            println!("It's warm outside.");
        } else {
            println!("It's cold but above freezing.");
        }
    } else {
        println!("It's freezing or below.");
    }
}
OutputSuccess
Important Notes

Keep nested conditions simple to avoid confusion.

You can use else if for cleaner multiple checks instead of deep nesting.

Summary

Nested conditions let you check one condition inside another.

They help make decisions step-by-step.

Use if, else if, and else to cover all cases.