Codecademy Logo

Control Flow

match

A match expression takes a pattern and compares it against any number of provided match arms. We can define match arms with => placed between the matched pattern and its resultant code block.

If the body of a match arm is a single statement or expression, we must terminate the block with a ,.

// Using a match expression to test a boolean value:
let there_are_birds = true;
match there_are_birds {
true => println!("hooray!"),
false => {
println!("don't worry,");
println!("we can call for them.");
}
}

Ordering

Ordering on a type can be compared with <, >, <=, >=. These operators will work on any type which implements the Ord or PartialOrd traits.

let pancakes = 10;
if pancakes < 3 {
println!("Eat more pancakes.")
} else if pancakes > 10 {
println!("Uh oh...")
} else if pancakes == 10 {
println!("That's a lot of pancakes")
} else {
println!("Mmm syrup")
}

Equality

Equality can be checked with == and non-equality with !=. These operators will work on any type which implements the Eq or PartialEq traits.

let track_number = 8;
if track_number == 9 {
println!("number nine");
}
if track_number != 9 {
println!("flip the record");
}

Conditionals

In Rust, we can conditionally execute blocks of code based on the outcome of any boolean expression by utilizing the if keyword. To handle the remaining cases, we can use the else keyword. We can use else if to provide additional, conditional checks between if and else.

if num < 0 {
println!("negative");
} else if num > 0 {
println!("zero");
} else {
println!("positive");
}

Loops and Loop Labels

We can repeat a block of code endlessly with the loop statement. When we have multiple nested loops, we may want to break out of a parent loop directly rather than the one we are currently in. Rust allows us to tag our loops with labels utilizing the syntax `label: loop {}. We can then denote which loop we want to break out of by its label.

// Basic for loop
println!("This is the program that never ends...");
loop {
print!(" yes, it goes on and on, my friend,")
}
// Using loop labels
'first: loop {
println!("entering 'first");
'second: loop {
println!("entering 'second");
break 'first;
}
println!("I will never print")
}

break and continue

Code execution within a loop can be diverted at any point with the break and continue keywords. break will stop code execution and exit the loop, and continue will stop code execution and restart at the beginning of the loop.

loop {
println!("I will be printed once");
break;
println!("I will not be printed");
}
println!("that was fast");
loop {
print!(".");
continue;
println!("I will not be printed");
}
println!("I will also never print");

while Loops

We can repeat code based on a conditional evaluation with the while statement. Once the provided condition is satisfied, the loop will break.

We can destructure with a while statement using the while let pattern. This pattern operates much the same way an if let pattern does.

// a while loop
let mut number = 0;
while number <= 11 {
println!("{number}");
number += 2;
}
// a while-let loop
let mut timer = Some(10);
while let Some(seconds_left) = timer {
if seconds_left == 0 {
println!("done!");
timer = None;
} else {
println!("{seconds_left}");
std::thread::sleep_ms(1000);
timer = Some(seconds_left - 1);
}
}

for-in Loops

It is possible to iterate over the items of a collection utilizing the for and in keywords. Any collection which implements the std::iter::Iterator trait can utilize this pattern.

let numbers = vec![10, 9, 8, 7, 6, 5, 4, 3, 2, 1,];
println!("the numbers are ");
// Here n is a newly created variable for each item of our collection.
for n in numbers {
println!("{n} ");
}

Learn more on Codecademy