Rust - Control Flow: Loops
Control Flow: Loops
Rust has three kinds of loops: loop, while, for
.
loop
The loop
keyword creates an infinite loop.
loop {
println!("again!");
}
You might also need to pass the result of that operation out of the loop to the rest of your code.
To do this, you can add the value you want returned after the break
expression you use to stop the loop
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
Multiple Loops
You can optionally specify a loop label on a loop that you can then use with break or continue
'counting_up: loop {
println!("count = {count}");
let mut remaining = 10;
loop {
println!("remaining = {remaining}");
if remaining == 9 {
break;
}
if count == 2 {
break 'counting_up;
}
remaining -= 1;
}
count += 1;
}
while
Conditional Loop, a combination of loop, if, else, break
while number != 0 {
println!("{number}!");
number -= 1;
}
for
Looping Through a Collection
for element in a {
println!("the value is: {element}");
}
Instead of using a while index < array_size
.
Increases the safety of the code and eliminated the chance of bugs that might result from going beyond the end of the array
We can also use to run some code a certain number of times
// countdown
for number in (1..4).rev() {
println!("{number}!");
}
################################################################################
################################################################################
################################################################################
Leave a Comment