use rand::Rng; use std::cmp::Ordering; use std::io;
/** * The main function of the program. * It starts the game by printing a welcome message, generating a secret number, and then entering a loop where it prompts the user to guess the number. * It continues to loop until the user guesses the correct number. */ fnmain() { println!("Guess the number!");
/** * Generates a secret number between 1 and 100 (inclusive) using the `rand::thread_rng().gen_range(1..101)` function. * This number will be the target that the user will try to guess. */ letsecret_number = rand::thread_rng().gen_range(1..101);
/** * The main game loop. It will continue to run until the user guesses the correct number. */ loop { println!("Enter your guess: ");
/** * Reads a line of input from the user. * If the input cannot be read, the program will panic with the message "Failed to read line". */ letmut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line");
/** * Parses the user's input into a u32 integer. * If the input cannot be parsed, the program will skip the current iteration of the loop and continue to the next one. */ letguess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, };
println!("You guessed: {}", guess);
/** * Compares the user's guess with the secret number. * If the guess is less than the secret number, it prints "Too small!". * If the guess is greater than the secret number, it prints "Too big!". * If the guess is equal to the secret number, it prints "You got it!" and breaks out of the loop. */ match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You got it!"); break; } } } }