What a while loop does
A while loop repeats a block of code as long as a condition is true. Before every pass, Rust evaluates the condition. If it is true, the block runs. If it is false, the loop ends and the program continues with the line after the closing brace.
The general shape is:
while condition {
// statements to repeat
}
Rust does not use parentheses around the condition, and the braces are always required, even when the body is a single statement. The condition must be a bool. Unlike some languages, Rust does not treat the number 1 or a non-empty string as "true": while 1 {} is a type error.
A counter-controlled loop
The most common use of while is a counter: a variable that starts at some value, is tested in the condition, and is changed inside the body. Here it is with output:
let mut count = 1;
while count <= 5 {
println!("I made a mistake");
count += 1;
}
println!("Finished!");
This prints I made a mistake five times, then Finished!. Follow the values of count:
countis 1. Is1 <= 5? Yes, so print and makecount2.- 2, 3, 4 and 5 pass the same test, and each pass adds 1.
- After the pass with 5,
countis 6. Is6 <= 5? No, so the loop ends. - The program continues and prints
Finished!.
The body ran five times because the values 1, 2, 3, 4 and 5 pass the test. The test is also checked one extra time, with 6, to find out that it is time to stop. A while loop whose condition is false the very first time runs zero times.
A while loop is like an if statement that jumps back and checks again after each run.
Three parts every counter loop needs
- Initialization: the counter gets its starting value before the loop.
- Condition: a test on the counter, written after
while. - Update: a statement in the body that moves the counter toward making the condition false.
If any of the three is missing or wrong, the loop prints the wrong number of times or never stops.
The exercise, step by step
The lesson asks for the message I promise to learn coding. five times, using a loop. The steps build the loop one piece at a time.
- Declare the counter with
let mut counter = 1;. Themutis needed: Rust variables are immutable by default, and this loop changescounter. Withoutmut, the update line fails to compile withcannot assign twice to immutable variable. - Write the loop header with the condition
counter <= 5. Starting at 1 and using<=means the body runs for 1, 2, 3, 4 and 5, which is five times. - Print the message inside the braces with
println!. - Increase the counter with
counter += 1;. Rust has no++operator, so+= 1is the way to write it.
Put together:
let mut counter = 1;
while counter <= 5 {
println!("I promise to learn coding.");
counter += 1;
}
It prints the message on five lines.
Common mistakes
- Forgetting the update. If
counter += 1;is missing,counterstays 1, the condition stays true, and the loop prints forever. The compiler may even warn that the variable does not need to be mutable, which is a hint that nothing in the loop changes it. - An off-by-one in the condition. Starting at 1 with
counter < 5prints four times. Starting at 0 withcounter <= 5prints six times. Decide the first value, the last value and whether the comparison includes the last one. - Forgetting
mut. The compiler tells you and suggests adding it. - Using
=instead of==or<=in the condition. A single=assigns; it is not a comparison. - Putting the update after the loop, outside the braces. Then it runs only once, after the loop has finished.
Key takeaways
while condition { ... }checks the condition before each pass and repeats while it istrue.- The condition has no parentheses, must be a
bool, and the braces are required. - A counter needs an initial value, a test and an update, and it must be declared with
let mutbecause it changes. - Use
counter += 1; Rust has no++. - If the condition is false from the start, the body never runs.
