Control flow is a fundamental aspect of programming that allows developers to dictate the execution path of their code based on certain conditions or loops. In Rust, a modern systems programming language, control flow is implemented through constructs like if expressions and loops. Let's delve into these concepts to better understand how they work in Rust.
If Expressions
The `if` expression in Rust is a powerful tool for making decisions in your code. It allows you to execute a block of code based on whether a given condition is true or false. Here's a simple example:
Rust
fn main() {
let number = 3;
if number < 5 {
println!("condition was true");
} else {
println!("condition was false");
}
}
In this example, the program checks if the value of `number` is less than 5. If the condition is true, it executes the code inside the first block; otherwise, it runs the code inside the `else` block.
Rust enforces that the condition in an `if` statement must be a boolean. Unlike some other languages, Rust does not automatically convert non-boolean types to a boolean. For example, the following code will result in a compilation error:
Rust
fn main() {
let number = 3;
if number {
println!("number was three");
}
}
The error message indicates that Rust expected a boolean but received an integer.
To handle multiple conditions, you can use `else if` expressions, as demonstrated in the following example:
Rust
fn main() {
let number = 6;
if number % 4 == 0 {
println!("number is divisible by 4");
} else if number % 3 == 0 {
println!("number is divisible by 3");
} else if number % 2 == 0 {
println!("number is divisible by 2");
} else {
println!("number is not divisible by 4, 3, or 2");
}
}
This code checks multiple conditions sequentially and executes the block associated with the first true condition.
An interesting feature of Rust is that `if` can be used as an expression, allowing you to assign its result to a variable. For example:
Rust
fn main() {
let condition = true;
let number = if condition { 5 } else { 6 };
println!("The value of number is: {number}");
}
Here, the variable `number` will be assigned the value of either 5 or 6 based on the condition.
Loops
Loops are essential for repeating code execution, and Rust provides three types of loops: `loop`, `while`, and `for`.
`loop`
The `loop` keyword instructs Rust to execute a block of code indefinitely until explicitly told to stop. An example is given below:
Rust
fn main() {
loop {
println!("again!");
}
}
To exit a `loop`, you can use the `break` keyword, as shown in the following example:
Rust
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
println!("The result is {result}");
}
In this example, the loop runs until the `counter` reaches 10, at which point it breaks and returns the value `counter * 2`.
`while`
The `while` loop allows you to repeatedly execute a block of code as long as a given condition is true. Here's an example:
Rust
fn main() {
let mut number = 3;
while number != 0 {
println!("{number}!");
number -= 1;
}
println!("LIFTOFF!!!");
}
This code counts down from 3 to 1, printing the current value at each step, and then prints "LIFTOFF!!!" after the loop.
`for`
The `for` loop in Rust is primarily used for iterating over a collection of items. It is concise and safer than manually managing indices. Here's an example:
Rust
fn main() {
let a = [10, 20, 30, 40, 50];
for element in a {
println!("the value is: {element}");
}
}
In this example, the loop iterates over each element in the array `a`, printing the value. The `for` loop eliminates the need to manually manage indices and enhances code safety.
Additionally, you can use a `for` loop with a range to achieve tasks like counting down, as shown below:
Rust
fn main() {
for number in (1..4).rev() {
println!("{number}!");
}
println!("LIFTOFF!!!");
}
This code counts down from 3 to 1 using a range and the `rev` method.