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

Rust: loop with break

  • loop

  • break

  • If we cannot have the condition at the top of the loop, in some languages we write while true. In Rust we use loop.

  • We better have a condition with a break or we create an infinite loop!

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

fn main() {
    loop {
        let number = get_number();
        println!("number {}", number);
        if number == 42 {
            break;
        }
    }
}

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
}