Control Flow in Rust
Introduction
Control flow refers to the order in which individual statements, instructions, or function calls are executed or evaluated in a program. In Rust, control flow is primarily managed through conditional statements, loops, and function calls. This tutorial will cover the fundamental aspects of control flow in Rust, providing examples and explanations for each concept.
Conditional Statements
Conditional statements allow you to execute certain pieces of code based on whether a condition is true or false. The primary conditional statement in Rust is the if statement.
If Statement
The if statement evaluates a condition and executes a block of code if the condition is true.
Example:
let number = 5;
if number > 0 {
println!("The number is positive!");
}
In this example, if the variable number
is greater than 0, it prints "The number is positive!".
If-Else Statement
The if-else statement allows you to execute one block of code if the condition is true, and another block if it is false.
Example:
let number = -3;
if number > 0 {
println!("The number is positive!");
} else {
println!("The number is not positive!");
}
In this case, since number
is -3, the output will be "The number is not positive!".
Loops
Loops allow you to execute a block of code multiple times. Rust provides three types of loops: loop, while, and for.
Loop
The loop statement runs indefinitely until explicitly told to stop using break
.
Example:
let mut counter = 0;
loop {
println!("Counter: {}", counter);
counter += 1;
if counter >= 5 {
break;
}
}
This loop will print the counter value from 0 to 4, then exit.
While Loop
A while loop continues to execute as long as a specified condition is true.
Example:
let mut number = 1;
while number <= 5 {
println!("Number: {}", number);
number += 1;
}
This code will print numbers from 1 to 5.
For Loop
The for loop is used to iterate over a range or collection.
Example:
for number in 1..6 {
println!("Number: {}", number);
}
This will print numbers from 1 to 5, as the range 1..6
does not include 6.
Pattern Matching
Pattern matching is a powerful feature in Rust that allows you to compare a value against a series of patterns. The match statement is used for this purpose.
Example:
let number = 3;
match number {
1 => println!("One"),
2 => println!("Two"),
3 => println!("Three"),
_ => println!("Not one, two, or three"),
}
This will print "Three" since the variable number
matches the third pattern.
Conclusion
Control flow is a fundamental concept in Rust programming that enables the development of dynamic and responsive applications. Understanding how to use conditional statements, loops, and pattern matching is essential for writing effective Rust code. With practice, you will become proficient in controlling the flow of your applications.