Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

While loop in Rust

  • while

  • We usually use a while loop if we don't know how many iterations we'll have to do.

use std::io;
use std::io::Write;

fn main() {
    let mut total = 0;
    while total < 10 {
        let number = get_number();
        total += number;
        println!("total {}", total);
    }
}

fn get_number() -> i32 {
    let mut number = String::new();

    print!("Please type in an integer: ");
    io::stdout().flush().expect("Oups");
    io::stdin()
        .read_line(&mut number)
        .expect("Failed to get input");

    let number: i32 = number.trim().parse().expect("Could not convert to i32");

    number
}