What Is Control Flow In Rust?

In Rust programming, control flow is the mechanism that determines how your code runs, like which statements execute, which branches are taken, and how loops behave in your code.

Without control flow, Rust programs are run in a straight line and are unable to make decisions or repeat actions. Control flow is a big step to becoming a confident Rust developer.

Learn these topics:

  1. Why Control Flow Is Important in Rust
  2. Conditional statements like if, else if, and else
  3. Loops: loop, while, and for
  4. Using match for branching
  5. Beginner-friendly, unique examples

Why Control Flow Is Important in Rust

We can create dynamic and responsive programs by controlling the flow. It’s used to:

  • Run conditions based on different blocks of code.
  • It can repeat multiple operations without duplicating code.
  • Handle multiple cases smoothly with pattern matching.

Rust provides control flow tools similar to other languages, but it adds safety, clarity, and flexibility with ensures fewer runtime errors.

Conditional Statements in Rust

Rust and other languages use if, else if, and else for decision-making. For example:

fn main() {
let temperature = 32;

if temperature > 35 {
println!("It's a very hot day!");
} else if temperature >= 20 {
println!("The weather is pleasant.");
} else {
println!("It's a bit chilly outside.");
}
}

Output:

Rust control flow statements

How this example works:

  • If the temperature is above 35, the first branch runs.
  • If not, but it’s at least 20, the second branch runs
  • Otherwise, the final else branch executes.

But in Rust, if is not just a control flow statement, it’s an expression, which means you can assign the result of an if to a variable directly.

For example:

fn main() {
let number = 5;

let result = if number % 2 == 0 {
"Even"
} else {
"Odd"
};

println!("The number is {}", result);
}

In this code:

  • The if expression returns either “Even” or “odd”.
  • That return value is directly stored in result.
  • There are no separate assignments inside each branch.

Now, understand how it is different from most other languages?

In languages like C, C++, and Java, if is a statement, not an expression, so you cannot directly use if to produce a value; you must use a ternary operator ( ?: ) or assign inside each branch.

Let’s understand through example:

int number = 5;
String result;

if (number % 2 == 0) {
result = "Even";
} else {
result = "Odd";
}

// Or use the ternary operator:
result = (number % 2 == 0) ? "Even" : "Odd";

This is a Java code and it needs a ?: because it itself can’t return a value.

Loops in Rust

Rust has three primary looping conditions:

  • loop – Runs your loop until explicitly stopped with break.
  • while – It runs while a condition remains true.
  • for – This iterates over ranges or collections.

Example 2: Let’s, we create a simple counter program using loop:

fn main() {
let mut count = 0;

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

if count == 5 {
println!("Reached 5, stopping!");
break;
}
}
}

This loop runs forever, but stops when the count reaches at 5 using the break statement.

output:

Counting: 1
Counting: 2
Counting: 3
Counting: 4
Counting: 5
Reached 5, stopping!

Example 3: Creating a countdown using a while statement.

fn main() {
let mut number = 3;

while number > 0 {
println!("Countdown: {}", number);
number -= 1;
}

println!("Lift off!");
}

Output:

Countdown: 3
Countdown: 2
Countdown: 1
Lift off!

Example 4: we using a for statement with a range

In this code, 1..=5 creates a range that includes 5, so the loop runs 5 times.

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

What is match statement in Rust?

match is a powerful control flow that allows pattern matching, and it’s more versatile and expressive than multiple if statements.

See the match statement with the simple Exam Scores program:

fn main() {
let score = 82;

match score {
90..=100 => println!("Excellent!"),
75..=89 => println!("Good job!"),
50..=74 => println!("Needs improvement."),
_ => println!("Failed."),
}
}

Output:

Good job!

First, match compares score to ranges, then _ is a catch-all pattern for any value not matched earlier.

Simple Exercises For Practice

Exercise 1: Daily Water Reminder

Write a Rust program with the following terms:

  1. Uses a for loop to print reminders 3 times (like morning, afternoon, evening).
  2. Each reminder should display the time of day and say “Drink a glass of water”.
  3. Print this line at to end of the program: “Stay hydrated today!”.

Match your output:

Morning: Drink a glass of water!
Afternoon: Drink a glass of water!
Evening: Drink a glass of water!
Stay hydrated today!

Exercise 2: Even or Odd Counter

Write a Rust program with the following terms:

  1. Uses a while loop to count from 1 to 5.
  2. For each number, check using an if condition whether it’s even or odd.
  3. Print the number followed by “is even” or “is odd”.

Match your output:

1 is odd
2 is even
3 is odd
4 is even
5 is odd

Leave a Comment