Hi, there! I'm very new to Rust and am working through the No Starch Press book. I've just finished the chapter on error handling and realized that the updated code in it for the Guessing Game panics anytime a user makes a guess of over 100 (which, I guess was the point).
I searched and found a few questions on this forum about the guessing game, but they were about different versions. Apologies if there's a dup I didn't find!
I have a solution and would love feedback on it. Specifically, is there a good way to reuse the error string from Guess::new()
?
extern crate rand;
use rand::Rng;
use std::cmp::Ordering;
use std::io;
fn guessing_game() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
println!("The secret number is: {}", secret_number);
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
let guess = match guess.trim().parse() {
Ok(num) => match num > 100 {
true => {
println!("Guess value must be between 1 and 100, got {}.", num);
continue;
}
false => Guess::new(num),
},
Err(_) => continue,
};
println!("You guessed: {}", guess.value());
match guess.value().cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}
pub struct Guess {
value: u32,
}
impl Guess {
pub fn new(value: u32) -> Guess {
if value < 1 || value > 100 {
panic!("Guess value must be between 1 and 100, got {}.", value);
}
Guess { value }
}
pub fn value(&self) -> u32 {
self.value
}
}