Objective
Loops and If-else statements
By the end of this lesson, you will understand how to implement control flow in Rust using if
statements, loop
, while
, and for
loops. You will learn how to make decisions in your code and iterate over collections.
1. If Statements
if
statements allow you to execute code based on a condition. Rust's if
statements can be used in a variety of ways, including with else
and else if
for additional conditions.
Basic If Statement:
let number = 10;
if number < 5 {
println!("The number is less than 5.");
} else {
println!("The number is 5 or greater.");
}
If with Else If:
let number = 10;
if number < 5 {
println!("The number is less than 5.");
} else if number < 15 {
println!("The number is between 5 and 15.");
} else {
println!("The number is 15 or greater.");
}
Returning a Value from If: In Rust, if
statements can also return values. This can be useful for assigning values based on conditions.
let number = 10;
let result = if number < 5 { "Less than 5" } else { "5 or more" };
println!("Result: {}", result);
2. Loops
Rust provides several ways to create loops: loop
, while
, and for
. Each serves a different purpose.
Infinite Loop with Loop: The loop
construct creates an infinite loop unless explicitly exited with a break
statement.
let mut count = 0;
loop {
if count >= 5 {
break; // Exit the loop when count reaches 5
}
println!("Count: {}", count);
count += 1;
}
While Loop: The while
loop continues executing as long as the given condition evaluates to true
.
let mut count = 0;
while count < 5 {
println!("Count: {}", count);
count += 1;
}
For Loop: The for
loop is used to iterate over collections, such as arrays or ranges. It is often the preferred loop in Rust due to its safety and expressiveness.
Iterating Over a Range:
for i in 0..5 {
println!("Count: {}", i);
}
Iterating Over an Array: You can also use a for
loop to iterate through an array or a vector.
let numbers = [1, 2, 3, 4, 5];
for number in numbers.iter() {
println!("Number: {}", number);
}
3. Match Statement
In addition to if
statements, Rust offers a powerful match
statement for pattern matching, which can often serve as a more elegant alternative to multiple if
statements.
Basic Match:
let number = 3;
match number {
1 => println!("One"),
2 => println!("Two"),
3 => println!("Three"),
_ => println!("Other"), // _ acts as a default case
}
4. Conclusion
In this lesson, you learned about control flow in Rust, focusing on if
statements and loops. You explored how to make decisions in your code and iterate over collections using loop
, while
, and for
. You also got a glimpse of the match
statement for pattern matching, providing more flexibility in handling multiple conditions.