I have fully coded the program from the book "Rust Programming Language" on the Internet, chapter 2 . I also developed it a little further than intended: adding a simple question / answer when the user starts playing again by typing "y".
However, I am experiencing a small error in my program. When the user prefers to start the game again, the output of the text "Please enter (number) guessing" is repeated twice. Of course, this does not mean that it does not distract from the main functionality of the program (it still functions normally after a repeat), but it seems strange, and I would prefer to remove the problem now, and not leave It.
I did some debugging, which led me to conclude that this is definitely happening in the area [figure 3] in the code. To find out how I did this, go to the debug area below.
the code
extern crate rand;
extern crate text_io;
use rand::Rng;
use std::io;
use std::cmp::Ordering;
fn main() {
println!("Guess the number!");
let mut breaking_choice = false;
while !breaking_choice {
let secret_number = rand::thread_rng().gen_range(1, 101);
loop {
println!("Please input a (number) guess");
println!("1");
let mut guess = String::new();
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
println!("2");
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small"),
Ordering::Greater => println!("Too big"),
Ordering::Equal => {
println!("Correct!");
break;
}
}
}
println!("Would you like to continue playing? Y or N");
let choice: String = read!();
if choice == "N" {
breaking_choice = true
} else if choice == "n" {
breaking_choice = true
} else if choice == "Y" {
continue;
} else if choice == "y" {
continue;
}
}
}
Debugging
The first thing I did was to place simple commands println!
in the main areas of processing dubious code: [Link 1] and [Link 2]. This allowed me to see if any of the teams was a problem between them, to give me a slightly better angle on what was happening. I also replaced the random number generator with a given number ( let secret_number = 5;
)
Here is what happened in the compilation:

and this happened at runtime:

From these results, I believe that the error occurs in [FIG. 3] (checking for basic input) because this is where it seems to stop.
println!("3");
//...until correct
, . [. 3] .