loop
202307071954
Status: #idea
Tags: Rust
loop
- Infinite loop
loop {
println!("Infinite loop");
}
Returning values from loop
- Add the return value after
break
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
}
println!("The value of result is {result}"); // 20
}
loop labels
- Used to uniquely identify loops when nested
- Must being with a single quote
'
Info
By default, break and continue affect the innermost loop
fn main() {
// ...
'counting_up: loop {
loop {
if condition_1 {
break; // Breaks inner loop
} else if condition_2 {
break 'counting_up;
} else if condition_3 {
continue 'counting_up;
}
}
}
}