Rust Loops
The loop{}
will start a loop until you tell it to break
let mut counter = 0;
loop{
counter += 1;
println!("The counter is {}", counter);
if counter == 5{
break;
}
}
Loops can be named as well, use a back tick, preferred name and a colon. They especially useful if you have a loop
in a loop
and what to directly call out the one to stop or break out from
`first_loop: loop {
//first loop body
`second_loop: loop {
if something_happens{
break `first_loop;
}
}
}
While Loop
A while
loop will continue while something is true and if it becomes false, Rust will stop the loop.
while true {
}
For Loop
A for
loop let you tell Rust what to do each time. It runs for a number of time instead of waiting for something to be false, for
loops use range often.
for number in 0..3{
println!({number});
}