Rust Tutorial
Estimated reading: 3 minutes 31 views

🔁 Rust Control Flow – If, Match, Loops, and Decisions

🧲 Introduction – Mastering Logic Flow in Rust

Control flow is the backbone of logic in programming. Rust gives you powerful constructs like if, match, while, and for to control execution paths safely and efficiently.

Unlike traditional languages, Rust’s control flow integrates tightly with its type system and safety model, ensuring logic is explicit, error-free, and compiler-verified.

🎯 In this guide, you’ll learn:

  • How to use if, else, and else if
  • How to replace switch with Rust’s powerful match
  • How to use loop, while, and for for iteration
  • Best practices for writing readable, safe logic

📘 Topics Covered

🔹 Topic📄 Description
🔀 Rust – If…ElseConditional branching using if, else if, and else.
🎯 Rust – MatchPowerful pattern matching alternative to switch in other languages.
🔎 Rust – Decision MakingMerged logic for combining if and match effectively.
🔁 Rust – LoopsOverview of all loop types in Rust.
🔄 Rust – While LoopLooping while a condition is true.
🔂 Rust – For LoopLooping over ranges, arrays, and iterators.

🔀 Rust – If…Else (Decision Making)

fn main() {
    let score = 85;

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

🧠 Explanation:

  • Conditions must evaluate to a bool.
  • Rust does not allow non-boolean values as conditions.
  • if can be used as an expression:
let is_even = if score % 2 == 0 { true } else { false };

🎯 Rust – Match Statement

Rust’s match is a powerful pattern matching tool.

fn main() {
    let day = 3;

    match day {
        1 => println!("Monday"),
        2 => println!("Tuesday"),
        3 => println!("Wednesday"),
        _ => println!("Other Day"),
    }
}

🧠 Features:

  • Exhaustive by default (must cover all cases or use _).
  • Can return values:
let result = match number {
    0 => "zero",
    1 => "one",
    _ => "other",
};

🔁 Rust – Loop (Infinite)

fn main() {
    let mut count = 0;

    loop {
        count += 1;
        println!("Count: {}", count);

        if count == 3 {
            break;
        }
    }
}

🧠 Loop Details:

  • Runs infinitely unless you use break.
  • Can return values:
let result = loop {
    if count > 5 {
        break count;
    }
    count += 1;
};

🔄 Rust – While Loop

fn main() {
    let mut x = 0;

    while x < 3 {
        println!("x = {}", x);
        x += 1;
    }
}

✅ Use while when:

  • The number of iterations is not known ahead of time.
  • You’re looping based on a condition.

🔂 Rust – For Loop

fn main() {
    for number in 1..=5 {
        println!("Number: {}", number);
    }
}

💡 Notes:

  • 1..=5 is an inclusive range (includes 5).
  • You can iterate over:
    • Arrays: for item in arr
    • Ranges: for i in 0..10
    • Iterators with .iter() or .enumerate()

🧠 Advanced Example:

let fruits = ["Apple", "Banana", "Cherry"];
for (index, fruit) in fruits.iter().enumerate() {
    println!("{}: {}", index, fruit);
}

📌 Summary – Recap & Next Steps

Rust’s control flow constructs allow you to express decisions, handle variants, and iterate over data in a safe and readable way. By enforcing conditions as bool and exhaustive pattern matching, Rust guarantees robust logic handling.

🔍 Key Takeaways:

  • Use if/else for simple condition checks.
  • match is exhaustive and great for branching logic.
  • loop provides infinite looping with break support.
  • while is best for condition-based iteration.
  • for is ideal for looping over ranges and collections.

⚙️ Real-World Applications:

  • CLI menu selection via match
  • Validation and branching logic with if/else
  • Iterating through config files or JSON data with loops

❓ Frequently Asked Questions

Does Rust support switch-case statements?
✅ No. Rust uses match instead, which is more powerful and exhaustive.


Can I return values from if or match?
✅ Yes. Both if and match are expressions in Rust and can return values.


What’s the difference between loop and while?
loop is infinite by default. while continues while a condition is true.


How to iterate in reverse using for?
✅ Use .rev():

for i in (1..=5).rev() {
    println!("{}", i);
}

Can I break or continue in loops?
✅ Yes. Use break to exit a loop and continue to skip to the next iteration.


Share Now :

Leave a Reply

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

Share

Rust Control Flow

Or Copy Link

CONTENTS
Scroll to Top