Loop of rust is very similar with python's loop.
We can use loop, while, for to make loop
loop is very simple infinite loop in rust.
fn main() {
let mut counter = 0;
loop {
counter += 1;
println!("counter is {}", counter);
if counter > 10 {
break;
}
}
}
Like the example above, loop doesn't have conditional so we have to break it manually. This is quite simple but not rusty style.
We can give a loop a name to tell the break statement which loop to break.
fn main() {
let mut counter = 0;
let mut counter2 = 0;
'first: loop {
counter += 1;
println!("the counter is: {}", counter);
if counter > 9 {
println!("now entering the second loop");
'second: loop {
println!("second counter is: {}", counter2);
counter2 += 1;
if counter2 == 3 {
break 'first;
}
}
}
}
}
This is the example of naming the loops. The break statement telling that it will break the first(outer) loop.
while is also same as the while of python.
counter = 0;
while counter != 5 {
counter += 1;
println!("{}", counter);
}
Also we can think it's loop + conditional expression.
Rust's for is same as the python's for. We use for..in expression.
for number in 0..3 {
println!("{}", number);
}
Also we have range expression(Definitely same as python).
When we use 0..3
, it means 0 1 2
(from 0, before 3), 0..=3
means 0 1 2 3
(from 0 to 3).
Like loop, we can also give a name to while, for loop.
And when we break the loop, we can return some value by break statement.
// break can have return value
counter = 5;
let number = loop {
counter += 1;
if counter %53 == 3 {
break counter;
}
};
println!("number is now: {}", number);
Like this example assigning the value to variable, we can send a return value when we break the loop.