🎓 A1Learner
🔍
0 of 142 lessons completed

Rust Guessing Game

A guessing game is a program that picks a secret number from 1 to 100 and answers each guess. Each answer is too small, too big, or a win.

The game needs a library

Rust's standard library has no random numbers, so the game borrows the rand crate. A crate is a package of Rust code that others can share and use. Add it under [dependencies] in Cargo.toml:

[dependencies]
rand = "0.10"

Pick the secret number

random_range(1..=100) picks from 1 to 100 — the = includes both ends:

let secret = rand::rng().random_range(1..=100);

Compare, answer, repeat

.cmp(&other) answers with an Ordering — Less, Greater or Equal. match turns each answer into a message, loop asks again, and break leaves the loop on a win. (The reading lines sit between the loop and the match in the full program below.)

loop {
    match guess.cmp(&secret) {
        Ordering::Less => println!("Too small!"),
        Ordering::Greater => println!("Too big!"),
        Ordering::Equal => { println!("You win!"); break; }
    }
}

A bad answer just asks again

parse hands back a Result. Ok holds the value, and Err holds the error. match guards the parse. Ok keeps the number. Err(_) uses continue to skip to the next round. A word instead of a number never crashes the game:

let guess: u32 = match guess.trim().parse() {
    Ok(n) => n,
    Err(_) => continue,
};

Example

use std::cmp::Ordering;
use std::io;
use rand::prelude::*;
fn main() {
    let secret = rand::rng().random_range(1..=100);
    loop {
        println!("Please input your guess.");
        let mut guess = String::new();
        io::stdin().read_line(&mut guess).expect("failed to read line");
        let guess: u32 = match guess.trim().parse() { Ok(n) => n, Err(_) => continue };
        println!("You guessed: {guess}");
        match guess.cmp(&secret) {
            Ordering::Less => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal => { println!("You win!"); break; }
        }
    }
}

Key points

  • A version like "0.10" follows semver (semantic versioning).
  • Cargo may update it only in ways that promise not to break your code.

In this example, the output shows one possible run, where the secret number was 37. First, random_range picks the secret from 1 to 100. Each loop round asks for a guess, reads a line, and parses it. A word instead of a number lands in Err(_). Then continue quietly asks again. A good guess is compared with cmp. 50 is Greater than the secret, so: Too big! 25 is Less: Too small! 37 is Equal, so the game prints You win! and break ends the loop — and the program.

Note

The _ in Err(_) is a catch-all.

It matches any error value, whatever is inside it.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

What does guess.cmp(&secret) give you?