Rust Control Flow
Estimated reading: 3 minutes 25 views

🦀 Rust – Decision Making: Control Flow Using if, else, and match

🧲 Introduction – Why Learn Decision Making in Rust?

Decision making in Rust is powered by a strong type system and expression-oriented syntax. It uses if, else, and match to control program behavior based on runtime conditions. These tools form the foundation of logic in Rust, enabling readable, robust, and type-safe flow control.

🎯 In this guide, you’ll learn:

  • How to use if, else if, and else
  • How to write conditional expressions
  • How match works as a powerful decision-making tool
  • Code examples with output and step-by-step explanations

if…else – Basic Conditional Logic

🔹 Code Example:

fn main() {
    let temperature = 22;

    if temperature > 30 {
        println!("It's hot today!");
    } else if temperature >= 20 {
        println!("Nice and warm.");
    } else {
        println!("It's chilly.");
    }
}

🧠 Explanation:

  • temperature is evaluated through multiple if…else if…else conditions.
  • Only the first true block executes.
  • Here, 22 >= 20 is true → it prints "Nice and warm."

📤 Output:

Nice and warm.

🧠 if as an Expression

🔹 Code Example:

fn main() {
    let score = 75;

    let result = if score >= 50 {
        "Pass"
    } else {
        "Fail"
    };

    println!("Result: {}", result);
}

🧠 Explanation:

  • if is used as an expression that returns a value.
  • result is assigned "Pass" or "Fail" based on condition.

📤 Output:

Result: Pass

🛠️ Nested if for Deep Decisions

🔹 Code Example:

fn main() {
    let number = -10;

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

🧠 Explanation:

  • Demonstrates nested conditionals.
  • Since number < 0, it prints "Negative".

📤 Output:

Negative

✅ Prefer else if over nested if for better readability when possible.


🧩 Using match for Multi-Condition Decision Making

🔹 Code Example:

fn main() {
    let traffic_light = "green";

    match traffic_light {
        "red" => println!("Stop"),
        "yellow" => println!("Wait"),
        "green" => println!("Go"),
        _ => println!("Invalid color"),
    }
}

🧠 Explanation:

  • match compares traffic_light against known values.
  • It prints "Go" when matched with "green".

📤 Output:

Go

🔁 Match as an Expression

🔹 Code Example:

fn main() {
    let day = 6;

    let day_type = match day {
        1..=5 => "Weekday",
        6 | 7 => "Weekend",
        _ => "Invalid",
    };

    println!("It's a {}", day_type);
}

🧠 Explanation:

  • Pattern matches ranges (1..=5) and multiple values (6 | 7).
  • Returns "Weekend" for day = 6.

📤 Output:

It's a Weekend

⚠️ Common Mistakes in Rust Decision Making

MistakeProblemSolution
Using non-boolean with ifCompile-time errorUse conditions that return bool
Mismatched return types in branchesType mismatch in if or matchEnsure all branches return same type
Missing wildcard _ in matchNon-exhaustive pattern errorAdd _ => "default" arm
Forgetting {} in ifOnly next line is controlled, can cause logic bugsAlways use {} even for one-liners

📌 Summary – Recap & Next Steps

Rust provides clear, type-safe, and expressive decision-making tools through if…else and match. Whether you’re checking a simple condition or pattern matching complex inputs, these constructs help structure robust control flow logic.

🔍 Key Takeaways:

  • Use if…else for basic, boolean-based decisions
  • Treat if as an expression for inline logic
  • Use match for multi-branch and pattern-based decisions
  • Always return consistent types and use exhaustive handling in match

⚙️ Next, explore Rust – Loops to learn how to repeat logic with loop, while, and for.


❓FAQs


Why does Rust require a boolean in if conditions?
✅ Rust enforces type safety. You must provide true or false—not integers like in C or JavaScript.


Can I use match instead of long if…else if chains?
✅ Yes. match is often cleaner and more readable when handling multiple discrete values or patterns.


What happens if I don’t use a default (_) case in match?
❌ Rust will raise a compile-time error unless all patterns are matched or a wildcard (_) is used.


Does if always need an else?
✅ No. But if used as an expression, both branches are required to return a value.


Share Now :

Leave a Reply

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

Share

Rust – Decision Making (merged with If…Else concepts)

Or Copy Link

CONTENTS
Scroll to Top