We usually use a while loop if have a simple condition to end the loop, but we don't know up-front how many iterations we are going to need to reach that condition.
For example we are generating random numbers between 1-10 and we would like to stop when their sum passes 50.
examples/while-loop/src/main.rs
use rand::Rng;
fn main() {
let mut total = 0;
while total < 50 {
let number = rand::thread_rng().gen_range(1..=10);
total += number;
println!("{total}");
}
}
Dependency
We use the rand crate as we have also seen in the generate random numbers example.
examples/while-loop/Cargo.toml
[package]
name = "while-loop"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rand = "0.8.5"
random = "0.14.0"