Rust Control Flow
Estimated reading: 4 minutes 26 views

🦀 Rust – If…Else: Conditional Logic with Code, Output & Explanation

🧲 Introduction – Why Learn if…else in Rust?

The if…else construct is at the heart of decision-making in any language. Rust brings its own safe and expressive twist—ensuring all conditions are explicitly boolean and supporting if as an expression that can return values.

🎯 In this guide, you’ll learn:

  • How to write if, else if, and else conditions
  • How to use if as an expression for assignments
  • Output and line-by-line breakdown of examples
  • Common pitfalls and best practices

✅ Basic if…else in Rust

🔹 Code Example:

fn main() {
    let age = 18;

    if age >= 18 {
        println!("You are an adult.");
    } else {
        println!("You are a minor.");
    }
}

🧠 Explanation:

  • let age = 18; → Declares an immutable variable age with value 18.
  • if age >= 18 → Condition checks if the value is 18 or more.
  • println!("You are an adult."); → Executed if condition is true.
  • else { println!("You are a minor."); } → Fallback block if condition is false.

📤 Output:

You are an adult.

➕ Multiple Conditions Using else if

🔹 Code Example:

fn main() {
    let score = 80;

    if score >= 90 {
        println!("Grade: A");
    } else if score >= 75 {
        println!("Grade: B");
    } else {
        println!("Grade: C");
    }
}

🧠 Explanation:

  • score is checked against two thresholds using chained conditions.
  • Only the first true condition block is executed.
  • else if score >= 75 is true here, so it prints "Grade: B".

📤 Output:

Grade: B

🧠 if as an Expression (Ternary Alternative)

🔹 Code Example:

fn main() {
    let is_logged_in = true;

    let status = if is_logged_in {
        "Welcome back!"
    } else {
        "Please log in."
    };

    println!("{}", status);
}

🧠 Explanation:

  • if is_logged_in evaluates to true.
  • "Welcome back!" is returned and assigned to status.
  • println! displays the result.

📌 Note: Both branches return &str (same type) – required by the compiler.

📤 Output:

Welcome back!

🔁 Nested if Blocks

🔹 Code Example:

fn main() {
    let number = 0;

    if number > 0 {
        println!("Positive");
    } else {
        if number < 0 {
            println!("Negative");
        } else {
            println!("Zero");
        }
    }
}

🧠 Explanation:

  • Checks if number > 0 → false
  • Inner if number < 0 → also false
  • Falls through to the final else

📤 Output:

Zero

✅ You can refactor this using else if for better readability.


⚠️ Common Mistakes with if…else

MistakeError Message or IssueFix
Using = instead of ==Assigns instead of comparesUse == for comparisons
Non-boolean conditionCompiler errorConditions must return true or false
Mismatched branch typesType inference failureEnsure both branches return same type
Missing braces {}Ambiguous logic or compile errorsAlways use braces—even for one-liners

🎭 Using if in Assignments

🔹 Code Example:

fn main() {
    let temp = 30;

    let comfort = if temp > 25 {
        "Hot"
    } else if temp >= 18 {
        "Pleasant"
    } else {
        "Cold"
    };

    println!("Weather: {}", comfort);
}

🧠 Explanation:

  • temp is checked in a chain of if…else if…else.
  • "Hot" is assigned to comfort since temp > 25.

📤 Output:

Weather: Hot

📌 Summary – Recap & Next Steps

The if…else construct in Rust gives you precise control over logic flow, all while enforcing strict type safety. By treating if as an expression, you can streamline value assignment and avoid verbose branching.

🔍 Key Takeaways:

  • Rust conditions must be boolean (no implicit coercion)
  • if can be used as an expression that returns values
  • Always use the same type for each branch of a value-returning if
  • Prefer else if over deeply nested if blocks

⚙️ Up Next: Learn about the powerful pattern-matching feature in Rust – Match (Switch Equivalent).


❓FAQs


Can I use if as a value in Rust like the ternary operator?
✅ Yes. Use if…else as an expression to return values:

let result = if x > 0 { "positive" } else { "non-positive" };

Why does Rust disallow using numbers as conditions?
✅ Rust enforces type safety. You must provide a bool, not an integer. This prevents bugs like if (x = 5) in other languages.


What happens if the two branches return different types?
❌ Compile-time error. Rust will not compile unless both branches return the same type.


Is else if mandatory?
✅ No. You can chain plain if statements, but else if is cleaner and more idiomatic.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Rust – If…Else

Or Copy Link

CONTENTS
Scroll to Top