Rust Loops
Computers never get bored. If you need to do something a hundred times, a loop does it for you. Rust has three kinds of loops: loop, while and for. This page covers the first two, and the next page is all about for, the one you will use most.
loop: repeat until told to stop
loop repeats its block forever, until you stop it with break. That sounds dangerous, but it is perfect when you do not know in advance how many times you need to repeat, only when to stop.
fn main() {
let mut count = 1;
loop {
println!("Count: {}", count);
if count == 3 {
break;
}
count += 1;
}
println!("Done!");
}Count: 1 Count: 2 Count: 3 Done!
A loop can even hand back a value when it stops. Put the value after break:
fn main() {
let mut n = 1;
let first_big_square = loop {
if n * n > 50 {
break n * n;
}
n += 1;
};
println!("The first square above 50 is {}", first_big_square);
}The first square above 50 is 64
while: repeat while a condition is true
A while loop checks a condition before each round. As long as the condition is true, it runs the block again. As soon as it becomes false, the loop ends.
fn main() {
let mut savings = 1000;
let mut months = 0;
while savings < 2000 {
savings += 300;
months += 1;
}
println!("After {} months you have {} rupees", months, savings);
}After 4 months you have 2200 rupees
continue: skip to the next round
continue skips the rest of the current round and jumps to the next one. Here we print only the odd numbers:
fn main() {
let mut i = 0;
while i < 8 {
i += 1;
if i % 2 == 0 {
continue;
}
print!("{} ", i);
}
println!();
}1 3 5 7
A word about endless loops
If the condition of a while never becomes false, or a loop never reaches break, the program runs forever. Everyone writes one of these sooner or later, so do not worry. In our editor a program that runs too long without waiting for input is stopped with a message, and you can always press Ctrl+C in the terminal.
Practice exercises
- Use
whileto print a countdown from 10 to 1, then "Lift off!". - Use
loopandbreakto find the first number above 100 that is divisible by 7. - Print the numbers from 1 to 20, skipping the multiples of 3 with
continue.