The loop statement defines an infinite loop.
As an example, the following loop would never end:
loop {
println!("Hello!");
}10.2.1break¶
Using the break keyword, we may leave the loop at any moment:
let mut i = 0;
loop {
if i > 4 {
break;
}
print!("{i}, ");
i += 1;
}()The break keyword allows us to return a value:
let mut i = 0;
let n = loop {
if i > 3 {
break 15;
}
i += 1;
};
n1510.2.2continue¶
Using the continue keyword, we can also skip the current step and go to
the next:
let mut i = 0;
loop {
i += 1;
if i % 2 == 0 {
continue;
}
if i > 8 {
break;
}
print!("{i}, ");
}()10.2.3Nested loops¶
Exiting from nested loops is best done using a label:
let mut i = 0;
let mut j = 0;
'my_label: loop {
i += 1;
loop {
j += 1;
if i+j > 7 {
break 'my_label;
}
}
}
(i, j)(1, 7)