Control Flow in Rust: A Comprehensive Guide

A guide to Rust conditions and loops, including expression values, labelled breaks, iterators, and ranges. Correctly distinguish a branch value from returning from a function.

Rust control flow covers conditional values with if and repeated work with loop, while, and for. This guide builds on Rust functions and tail expressions to explain branch values, loop exits, labels, and ranges.

Conditional Statements: if, else if, and else

Rust’s if statements provide a way to execute code conditionally. Unlike many other languages, Rust does not require parentheses around conditions, making the syntax cleaner and more readable. Additionally, Rust’s if is an expression, not a statement, meaning it can return a value.

Key Points:

  1. No Semicolons: Rust requires no semicolons after the branch values of if statements. This ensures that the final expression in a block is returned as a tail expression.
  2. Consistent Return Types: All branches of an if expression must return the same type. Rust’s strong typing ensures type safety by enforcing this rule.
  3. Early Returns: You can use return inside an if branch. It exits the enclosing function. A tail expression instead supplies the branch’s value. The Rust Reference includes an early return inside an if block.

Here’s an example of using if expressions in Rust:

let num = 6;
let msg = if num == 5 {
    "five"
} else if num == 4 {
    "four"
} else {
    "other"
};
println!("The number is {}", msg);
Rust

In this code, msg is assigned the result of the if expression, which depends on the value of num.

Unconditional Loops: loop

Rust’s loop repeats its body until control leaves it, for example through break, return, or a panic. Use it when the exit condition belongs inside the loop rather than at the top.

Example:

loop {
    println!("Loop forever!");
}
Rust

You can exit the loop using break:

loop {
    println!("Loop forever!");
    break; // exit the loop
}
Rust

To handle nested loops, Rust allows you to use labels. This lets you break out of an outer loop from within an inner loop:

'outer: loop {
    println!("Entered the outer loop");
    'inner: loop {
        println!("Entered the inner loop");
        break 'outer; // exit the outer loop
    }
    println!("This point will never be reached");
}
Rust

while Loops

The while loop in Rust executes code as long as a specified condition is true. It’s essentially syntactic sugar for a loop with an if condition to check and a break statement to exit:

while condition {
    // code
}
Rust

Rust does not have a do-while loop, but you can achieve similar functionality by using loop with an if condition.

for Loops

The for loop in Rust iterates over elements of a collection or a range. It’s concise and expressive, making it ideal for iterating over arrays, vectors, and ranges.

Examples:

for num in [1, 2, 3].iter() {
    println!("{}", num);
}
Rust

You can also use functional programming methods like map, filter, and fold with iterators:

[1, 2, 3].iter()
    .map(|num| num * num)
    .for_each(|num| println!("{}", num));

[1, 2, 3].iter().fold(0, |acc, num| acc + num);
Rust

Working with Ranges

Ranges provide a concise way to iterate over a sequence of numbers. Rust’s ranges are inclusive at the start and exclusive at the end:

for num in 1..4 {
    println!("{}", num);
}
Rust

This code will print 1, 2, and 3.

Conclusion

Use if for conditional values, while for a condition checked before each iteration, and for for iterator-driven work. An ordinary start..end range excludes its end; start..=end includes it. Try the loops with Rust arrays and continue through the Rust Fundamentals series.

Share
Prabhat Kashyap

Prabhat Kashyap

Senior Technical Architect at HCLTech · working with Leonteq Security AG

I have 10+ years of experience building distributed systems and fintech platforms. I write about practical, non-obvious engineering details that official documentation often skips.

Newsletter

Get new engineering deep dives

Scala, JVM, AI, and backend systems. I send practical articles when there is something worth reading.

Join the newsletter