Start Coding

Control Flow in Rust

Control flow is a fundamental concept in Rust programming. It allows developers to direct the execution path of their code based on conditions and repetitions. Understanding control flow is crucial for writing efficient and logical Rust programs.

If Statements

If statements in Rust enable conditional execution of code blocks. They evaluate a boolean expression and execute the corresponding block if the condition is true.


let number = 5;

if number < 10 {
    println!("The number is less than 10");
} else if number == 10 {
    println!("The number is exactly 10");
} else {
    println!("The number is greater than 10");
}
    

Loops

Rust provides several types of loops for repetitive tasks:

1. loop

The loop keyword creates an infinite loop that can be broken using the break statement.


let mut counter = 0;

loop {
    println!("Counter: {}", counter);
    counter += 1;
    if counter == 5 {
        break;
    }
}
    

2. while

While loops continue executing as long as a condition remains true.


let mut number = 3;

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

println!("LIFTOFF!!!");
    

3. for

For loops iterate over elements in a collection or a range.


for number in (1..4).rev() {
    println!("{}!", number);
}
println!("LIFTOFF!!!");
    

Pattern Matching with match

The match expression in Rust provides powerful pattern matching capabilities. It's similar to a switch statement in other languages but offers more flexibility and safety.


let dice_roll = 3;

match dice_roll {
    3 => println!("You rolled a three!"),
    7 => println!("Lucky seven!"),
    _ => println!("You rolled something else"),
}
    

Important Considerations

  • Rust's if statements don't require parentheses around the condition.
  • The condition in an if statement must be a boolean expression.
  • Use break to exit a loop early and continue to skip to the next iteration.
  • The match expression must be exhaustive, covering all possible cases.

Mastering control flow is essential for writing efficient Rust code. It allows you to create more complex and dynamic programs. As you progress, you'll find these concepts integrating seamlessly with other Rust features like ownership and pattern matching.

For more advanced control flow techniques, explore iterators and Result enum for error handling. These concepts build upon the foundational control flow structures and provide more sophisticated ways to manage program execution in Rust.