Rust If..Else

Making decisions and controlling program flow

🔀 What is Rust If..Else?

If..else statements in Rust allow your program to make decisions based on conditions. They execute different code blocks depending on whether conditions are true or false, enabling dynamic program behavior.


// Basic if..else example
let age = 18;
if age >= 18 {
    println!("You can vote!");
} else {
    println!("Too young to vote.");
}
                                    
If..Else Types

Types of Conditional Statements

🎯

Simple If

Execute code when condition is true

if temperature > 30 {
    println!("It's hot!");
}
⚖️

If..Else

Choose between two options

if is_sunny {
    println!("Go outside!");
} else {
    println!("Stay inside!");
}
🔗

Else If

Multiple conditions in sequence

if score >= 90 {
    println!("A grade");
} else if score >= 80 {
    println!("B grade");
}
📊

If Expression

Return values from if statements

let status = if online {
    "Connected"
} else {
    "Offline"
};

🔹 Basic If Statement

The simplest form of conditional execution:

fn main() {
    let temperature = 25;
    let is_raining = false;
    let has_umbrella = true;
    
    // Simple if statement
    if temperature > 20 {
        println!("It's a nice day!");
    }
    
    // If with boolean variable
    if is_raining {
        println!("Don't forget your umbrella!");
    }
    
    // If with logical operators
    if !is_raining && temperature > 15 {
        println!("Perfect weather for a walk!");
    }
    
    // If with complex condition
    if is_raining && has_umbrella {
        println!("You're prepared for the rain!");
    }
}

Output:

It's a nice day!

Perfect weather for a walk!

🔹 If..Else Statement

Choosing between two different actions:

fn main() {
    let age = 16;
    let has_license = false;
    let balance = 50.0;
    
    // Basic if..else
    if age >= 18 {
        println!("You are an adult.");
    } else {
        println!("You are a minor.");
    }
    
    // If..else with boolean
    if has_license {
        println!("You can drive!");
    } else {
        println!("You need a license to drive.");
    }
    
    // If..else with comparison
    if balance >= 100.0 {
        println!("You have enough money for the premium plan.");
    } else {
        println!("Consider the basic plan for ${:.2}.", balance);
    }
    
    // Nested if..else
    if age >= 16 {
        if has_license {
            println!("Ready to drive!");
        } else {
            println!("Time to get your license!");
        }
    } else {
        println!("Too young to drive.");
    }
}

Output:

You are a minor.

You need a license to drive.

Consider the basic plan for $50.00.

Time to get your license!

🔹 Else If Chains

Handling multiple conditions in sequence:

fn main() {
    let score = 85;
    let temperature = 22;
    let hour = 14;
    
    // Grade calculation
    if score >= 90 {
        println!("Grade: A - Excellent!");
    } else if score >= 80 {
        println!("Grade: B - Good job!");
    } else if score >= 70 {
        println!("Grade: C - Satisfactory");
    } else if score >= 60 {
        println!("Grade: D - Needs improvement");
    } else {
        println!("Grade: F - Please study more");
    }
    
    // Weather description
    if temperature > 30 {
        println!("It's very hot outside!");
    } else if temperature > 20 {
        println!("Nice and warm weather.");
    } else if temperature > 10 {
        println!("A bit cool, wear a jacket.");
    } else {
        println!("It's cold, bundle up!");
    }
    
    // Time of day
    if hour < 6 {
        println!("Very early morning");
    } else if hour < 12 {
        println!("Morning");
    } else if hour < 17 {
        println!("Afternoon");
    } else if hour < 21 {
        println!("Evening");
    } else {
        println!("Night");
    }
}

Output:

Grade: B - Good job!

Nice and warm weather.

Afternoon

🔹 If as Expression

Using if statements to return values:

fn main() {
    let age = 20;
    let is_weekend = true;
    let score = 95;
    
    // If expression assigning values
    let status = if age >= 18 {
        "Adult"
    } else {
        "Minor"
    };
    println!("Status: {}", status);
    
    // If expression with calculations
    let ticket_price = if age < 12 {
        5.0
    } else if age >= 65 {
        7.0
    } else {
        10.0
    };
    println!("Ticket price: ${:.2}", ticket_price);
    
    // If expression with complex logic
    let activity = if is_weekend && age >= 18 {
        "Go to the club"
    } else if is_weekend {
        "Play video games"
    } else {
        "Go to work/school"
    };
    println!("Suggested activity: {}", activity);
    
    // If expression with function calls
    let grade_letter = if score >= 90 {
        'A'
    } else if score >= 80 {
        'B'
    } else if score >= 70 {
        'C'
    } else {
        'F'
    };
    println!("Your grade: {}", grade_letter);
}

Output:

Status: Adult

Ticket price: $10.00

Suggested activity: Go to the club

Your grade: A

🔹 Complex Conditions

Combining multiple conditions with logical operators:

fn main() {
    let age = 25;
    let has_job = true;
    let credit_score = 750;
    let income = 50000;
    let has_debt = false;
    
    // Loan approval logic
    if age >= 18 && has_job && credit_score >= 700 {
        println!("Pre-approved for loan!");
    } else {
        println!("Loan application needs review.");
    }
    
    // Insurance premium calculation
    let is_young_driver = age < 25;
    let is_experienced = age > 30;
    let has_accidents = false;
    
    if is_young_driver && !has_accidents {
        println!("Standard premium for young driver");
    } else if is_experienced && !has_accidents {
        println!("Discounted premium for experienced driver");
    } else if has_accidents {
        println!("Higher premium due to accident history");
    } else {
        println!("Regular premium");
    }
    
    // Investment advice
    if income > 75000 && !has_debt && age < 40 {
        println!("Consider aggressive investment portfolio");
    } else if income > 40000 && age >= 40 {
        println!("Consider balanced investment portfolio");
    } else if has_debt {
        println!("Focus on paying off debt first");
    } else {
        println!("Start with conservative investments");
    }
}

Output:

Pre-approved for loan!

Regular premium

Start with conservative investments

🧠 Test Your Knowledge

What will this code print?
let x = if true { 5 } else { 10 };