while-loop in Rust

while rand random

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"

Related Pages

loops in Rust
loop in Rust
loop in Rust
loop in Rust

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo