Skip to content
Tutorials Center
My learning

Topics

Lesson 116 of 132 ยท Projects

Project: Guessing Game

Build a number guessing game in Rust in stages - reading input, parsing, Ordering, loops, a seeded random generator without crates, custom errors and tests with no keyboard needed.

The number guessing game is the classic first Rust project, and with good reason: in about a hundred lines it touches input and output, parsing, match, enums, loops and error handling. The computer picks a secret number; the player guesses; the program says "too low" or "too high" until the player wins.

We will not write it in one go. Real programs grow in small steps, each of which compiles and runs, and each step in this lesson is a complete program you can run in the editor. At the end we restructure it so that the game logic can be tested without a keyboard. Along the way you will meet the compiler errors beginners hit most often, with the real messages and the fixes.

Our editor has no Cargo and therefore no rand crate, so we also write a tiny random-number generator by hand. That is not just a workaround: it teaches how pseudo-random numbers work, and it makes the game reproducible, which is exactly what you want for testing. Because the editor cannot wait for you to type, every example that reads input has a preset Input box; edit it and run again to play different games. If you need a refresher, see Reading Input, match Expressions and Result and Error Handling.

Stage 1: read one line

std::io::stdin().read_line(&mut buffer) appends a line to a String, including the newline character, and returns the number of bytes read wrapped in an io::Result. That result must be handled; here we use expect to keep the first version short (a program that cannot read its own input has nothing sensible left to do).

Rust Stage 1: echo the guess

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The {line:?} debug format shows the string with its escape sequences. You will see the trailing \n when the input box ends with a newline; the program has no idea yet that "42" is a number.

Stage 2: parse and handle bad input

Text must be converted to a number with parse. It returns Result<T, E>, and the type T must be known. Forgetting to say which type is a very common first error:

Rust parse needs to know the target type (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The compiler answers error[E0282]: type annotations needed and suggests let guess: /* Type */ = .... Rust will not guess whether you meant u8, i64 or f32, because the answer decides which strings are valid. Write let guess: u32 = ... (a guess is never negative, so an unsigned type documents and enforces that) or use the turbofish parse::<u32>().

Users also type nonsense, and expect would crash on it. Handle the Err case with match:

Rust Stage 2: parse with match

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Change the input to abc, -5 (negative numbers are not valid u32), 99999999999999 (too big) or an empty line, and read the different messages that ParseIntError produces. The key idea: errors are values. The type system forces you to decide what happens in the Err case.

Stage 3: compare with Ordering

guess.cmp(&secret) returns an Ordering, an enum with exactly three variants: Less, Equal and Greater. Matching on it is the natural way to branch. Because match must be exhaustive, you cannot forget a case:

Rust A missing Ordering arm (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The message is error[E0004]: non-exhaustive patterns: std::cmp::Ordering::Equal not covered, which names the missing variant. Add the Equal arm and the program compiles. This safety net is why enums and match are so valuable: if you later add a fourth variant to your own enum, the compiler shows you every match that needs updating.

Types must match too. Comparing a u32 with an i32 is an error, not a silent conversion:

Rust Comparing different integer types (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

You get error[E0308]: mismatched types with the note "expected i32, found u32". Keep both sides u32 (see Type Conversion and Casting for when conversion is the right fix). Now put the pieces together for one round with a fixed secret:

Rust Stage 3: one comparison

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Stage 4: loop until the player wins

Now we repeat. Reading all of standard input line by line is the job of io::stdin().lines(), an iterator of io::Result<String> (the newline is already removed). A for loop works well here, and when the input ends (end of file) the loop simply stops, which means the program also behaves correctly when its input is piped from a file.

Rust Stage 4: the game loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

(The preset input has four lines.) Try removing the last line 37 from the input: the loop ends by itself and prints the final message. Observe that continue skips the rest of the iteration, so an invalid guess is not counted. If you were writing this for a terminal and wanted the prompt to wait for each line, lines() works unchanged, because it blocks until a full line arrives.

Stage 5: a secret that is not hard-coded

A computer cannot produce truly random numbers by arithmetic, but it can produce a pseudo-random sequence: a deterministic recipe that looks random. Start it from a number called the seed and the whole sequence is determined. We use the xorshift generator, which mixes the bits of a single u32 with three shifts and three XORs. It is tiny, fast and good enough for games (never for passwords or cryptography).

Rust Stage 5: a seeded random number generator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

For a real program you would depend on the rand crate. This is a read-only snippet, because the editor cannot download crates:

TOML
# Cargo.toml (read-only)
[dependencies]
rand = "0.9"
Rust
// src/main.rs (read-only): with rand 0.9
use rand::Rng;

fn main() {
    let secret: u32 = rand::rng().random_range(1..=100);
    println!("(debug) the secret is {secret}");
}

For testing, the seeded generator is better than a random secret: the same seed always produces the same game. In the next stage we use the fixed seed 2024, whose first number in the range 1 to 100 is 51. In a release you would seed from the clock as shown above.

Stage 6: structure the program

Our loop works but mixes everything in main: reading, parsing, game rules, printing. That makes it hard to test and to extend. Idiomatic Rust separates the pieces:

  • a GuessError enum for everything that can be wrong with input, with a friendly Display (Custom Error Types) and From<ParseIntError> so that the ? operator converts errors automatically (The ? Operator);
  • a parse_guess function that validates the range;
  • an Outcome enum (Won, Lost, Quit) returned by the game;
  • a play function that takes its input and output as parameters: any BufRead and any Write. In main they are the real keyboard and screen; in tests they are in-memory buffers.

We also add a limit of seven attempts (a binary search finds a number from 1 to 100 in at most seven guesses, so a perfect player can always win) and the command quit. The Input box below plays a game against the secret from seed 2024 (which is 51):

Rust Stage 6: the complete game

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Read play carefully, because it contains most of the lesson. input: &mut impl BufRead accepts anything you can read lines from. write!(output, ...)? propagates I/O errors with ? instead of unwrapping. The Lost result carries the secret so that main can reveal it. main returns io::Result<()>, so an I/O failure ends the program with an error message and a failure exit code (The main Function).

Because the guesses in the Input box are chosen for the secret 51, you see the full range of behavior in one run: a too-low guess, three kinds of invalid input (text, an empty line, a number out of range), two too-high guesses, then the win. Try changing the input to quit, or give seven wrong guesses.

Stage 7: test without a keyboard

Since play takes a reader and a writer, a test can feed it a script and inspect everything it printed. io::Cursor turns a byte slice into a BufRead, and a Vec<u8> is a Write. Here the checks run from main so you can run them in the editor (it prints "ok" for each); the complete program from Stage 6 is reused, with only main changed:

Rust Stage 7: scripted games as tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

In a real Cargo project the same checks live in a #[cfg(test)] mod tests block with #[test] functions, and you run them with cargo test (Testing). This is a read-only layout:

Rust
// src/main.rs (read-only): the same checks as unit tests
#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;

    #[test]
    fn wins_after_two_guesses() {
        let mut input = Cursor::new("50\n75\n");
        let mut output = Vec::new();
        let outcome = play(&mut input, &mut output, 75, 5).unwrap();
        assert_eq!(outcome, Outcome::Won { attempts: 2 });
    }
}

What you practiced, and how to extend it

You used read_line, lines, parse with explicit types, Ordering and exhaustive match, loop/for with continue, a custom error enum with Display and From, ? for propagation, an Outcome enum, generics with impl Trait parameters, a hand-written PRNG, and tests that need no terminal.

Ideas for your own version:

  • Ask for the range at the start (a small Settings struct) and compute the attempt limit as ceil(log2(range)).
  • Give "hot / cold" hints based on guess.abs_diff(secret).
  • Keep a history of guesses in a Vec and refuse repeats.
  • Add a scoreboard of the best (fewest) attempts, stored in a file (see Files and I/O).
  • Let the computer guess your number by binary search, with Ordering answers typed by you.

The next project, a command-line to-do manager, adds structs, a Vec of records and commands that change them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does let guess = line.trim().parse().expect("number"); fail to compile?

    parse::<F>() is generic over the target type. Without an annotation (or a later use that fixes the type) the compiler reports E0282, type annotations needed.
  2. 2. What does read_line do with the newline at the end of the line?

    read_line appends the whole line including \n (and \r\n on Windows). trim() removes it before parsing.
  3. 3. What is the benefit of play taking &mut impl BufRead and &mut impl Write instead of using stdin and println! directly?

    Cursor provides input and Vec<u8> collects output, so a test can run a whole game and assert on the transcript, without a keyboard.
  4. 4. Why does a seeded pseudo-random generator help when testing the game?

    A pseudo-random generator is deterministic. A fixed seed gives a reproducible secret, which a test (or a reader of this lesson) can rely on.
  5. 5. What happens if you forget the Ordering::Equal arm in the match?

    match must cover every variant. The compiler even names the missing one: Ordering::Equal not covered.

Summary

  • Build programs in small stages that each compile and run: read, parse, compare, loop, then restructure.
  • read_line keeps the newline; trim() then parse::<u32>() turns text into a number, and the target type must be stated.
  • Errors are values: handle Err with match, or convert and propagate with a custom error enum, From and ?.
  • Ordering has three variants and match forces you to handle all of them.
  • A pseudo-random generator is just a deterministic recipe plus a seed; seed it from the clock for variety or with a constant for tests (use the rand crate in real projects).
  • Pass readers and writers into your logic (impl BufRead, impl Write) so that it can be tested with Cursor and Vec<u8>.

Next: Project: Command-Line To-Do Manager