Rust LogoProgramming a Guessing Game

A guessing game is a classic introductory programming project that involves a user trying to guess a secret number generated by the computer. The game provides feedback to the user after each guess, indicating whether their guess was too high, too low, or correct. The game continues until the user successfully guesses the secret number.

This project is excellent for beginners as it covers several fundamental programming concepts:

1. Random Number Generation: The computer needs a way to generate a secret number randomly, which introduces the concept of using libraries or modules for specific functionalities (like `rand` in Rust).
2. Input/Output (I/O): The program must be able to read input from the user (their guess) and print output (instructions, feedback, and results) to the console.
3. Loops: The game needs to repeat the guessing process multiple times until the correct guess is made. This requires the use of loop constructs (e.g., `loop` or `while`).
4. Conditional Statements: After each guess, the program compares the user's guess to the secret number and makes decisions based on the comparison (e.g., `if`, `else if`, `else` or `match`).
5. Data Types and Type Conversion: User input is typically read as a string, but for numerical comparisons, it needs to be converted (parsed) into an integer. This highlights the importance of data types and type conversion.
6. Error Handling: Users might enter non-numeric input. A robust program should anticipate and handle such errors gracefully, preventing crashes and providing helpful messages.

The typical flow of a guessing game program is as follows:
1. Initialize the game by printing a welcome message and instructions.
2. Generate a random secret number within a predefined range.
3. Start an infinite loop for the guessing process.
4. Inside the loop:
a. Prompt the user to enter their guess.
b. Read the user's input.
c. Attempt to convert the input string to a number. If conversion fails, inform the user and ask for another guess (restarting the loop iteration).
d. Compare the user's number with the secret number.
e. Provide feedback: 'Too high!', 'Too low!', or 'You win!'.
f. If the guess is correct, exit the loop and end the game.

Example Code

use std::io; // Standard library input/output
use std::cmp::Ordering; // For comparing values (Less, Greater, Equal)
use rand::Rng; // For random number generation

fn main() {
    println!("Guess the number!");

    // Generate a random number between 1 and 100 (inclusive)
    let secret_number = rand::thread_rng().gen_range(1..=100);

    // For debugging, uncomment the line below to see the secret number
    // println!("The secret number is: {}", secret_number);

    loop { // Start an infinite loop
        println!("Please input your guess.");

        let mut guess = String::new(); // Create a mutable string to store user input

        io::stdin() // Get a handle to the standard input
            .read_line(&mut guess) // Read the line from stdin and put it into 'guess'
            .expect("Failed to read line"); // Handle potential errors

        // Convert the string guess to a number (u32 unsigned 32-bit integer)
        // trim() removes any whitespace including newlines
        // parse() converts the string to a number, returning a Result enum
        // match handles the Ok (success) or Err (failure) case
        let guess: u32 = match guess.trim().parse() {
            Ok(num) => num, // If parsing is successful, use the number
            Err(_) => { // If parsing fails (e.g., non-numeric input)
                println!("Please type a number!");
                continue; // Skip to the next iteration of the loop
            }
        };

        println!("You guessed: {}", guess);

        // Compare the guess with the secret number
        // cmp() returns an Ordering enum (Less, Greater, Equal)
        match guess.cmp(&secret_number) {
            Ordering::Less => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal => {
                println!("You win!");
                break; // Exit the loop if the guess is correct
            }
        }
    }
}