Rust
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; };
Exercise 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.
Show example solution
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;
}
}
}
}
Test yourself
-
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
- Panics
Show answer
Takes the Err arm and asks for a new guess — continue goes back to the start of the loop; the program doesn't crash.
-
Skip invalid input
let tahmin: u32 = match g.parse() {
Ok(n) => n,
Err(_) => ____,
};
Show answer
let tahmin: u32 = match g.parse() {
Ok(n) => n,
Err(_) => continue,
};
-
Keyword and effect
- loop
- Infinite loop
- break
- Exit the loop
- continue
- Go to the next round
- Err(_) =>
- Catch the error
Next lesson: Struct definition