CodeBlanks Logo Icon CodeBlanks

Loop and exit

End the game on a correct guess with loop and break.

Loop and ending

loop is used to repeat the game; on a correct guess we exit with break. On invalid input, instead of crashing the program, we continue using match:

loop {
    let mut tahmin = String::new();
    io::stdin().read_line(&mut tahmin).expect("okunamadı");
    let tahmin: u32 = match tahmin.trim().parse() {
        Ok(n) => n,
        Err(_) => continue,
    };
    match tahmin.cmp(&gizli) {
        Ordering::Less => println!("Çok küçük"),
        Ordering::Greater => println!("Çok büyük"),
        Ordering::Equal => { println!("Bildin!"); break; }
    }
}

Attempt counter

To enrich the game we can count the valid guesses. The counter is declared with let mut outside the loop, so its value is kept between rounds:

let mut deneme = 0;
loop {
    // ... a valid guess was read
    deneme += 1;
    if tahmin == gizli {
        println!("{deneme} denemede bildin!");
        break;
    }
}

break can be used with a value too: let sonuc = loop { break deneme; };

Practice Play the game

Run the game with gizli = 28 and the guess list ["50", "abc", "25", "28"]. Inside a loop, take the next guess with it.next() (break when it runs out). If invalid, print abc: Geçersiz and continue; if valid, increment the counter and print Büyük/Küçük; if equal, print 28: Bildin! (3 deneme) and break.

Starter code

main.rs
use std::cmp::Ordering;

fn main() {
    // buraya yaz
}

Sample solution

main.rs
use std::cmp::Ordering;

fn main() {
    let gizli: u32 = 28;
    let tahminler = ["50", "abc", "25", "28"];
    let mut it = tahminler.iter();
    let mut deneme = 0;
    loop {
        let g = match it.next() {
            Some(g) => g,
            None => break,
        };
        let t: u32 = match g.parse() {
            Ok(n) => n,
            Err(_) => {
                println!("{}: Geçersiz", g);
                continue;
            }
        };
        deneme += 1;
        match t.cmp(&gizli) {
            Ordering::Less => println!("{}: Küçük", t),
            Ordering::Greater => println!("{}: Büyük", t),
            Ordering::Equal => {
                println!("{}: Bildin! ({} deneme)", t, deneme);
                break;
            }
        }
    }
}

Expected output

50: Büyük
abc: Geçersiz
25: Küçük
28: Bildin! (3 deneme)

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 If the player enters <code>abc</code>, what does the loop above do?

  • Exits the loop
  • Treats it as 0
  • Takes the Err arm and asks for a new guess Correct answer
  • Panics

Explanation: continue goes back to the start of the loop; the program doesn't crash.

2 Skip invalid input

Question
let tahmin: u32 = match g.parse() {
    Ok(n) => n,
    Err(_) => ____,
};
Answer
let tahmin: u32 = match g.parse() {
    Ok(n) => n,
    Err(_) => continue,
};

Explanation: continue skips the invalid input and moves to the next round of the loop.

3 Keyword and effect

Term Meaning
loop Infinite loop
break Exit the loop
continue Go to the next round
Err(_) => Catch the error

All lessons in Beginner