· 2 min read

Rust 2: Guessing game

A guessing game to learn some rust-basics

Let’s check out a simple guessing game from the book “The Rust programming language” by Steve Klabnik and Carol Nichols, with contributions from the Rust community (2 ed).

Starting with cargo:

cargo new guessing_game

Adding rand as a dependency to generate random numbers, which we will use. In Cargo.toml:

[package]
name = "guessing_game"
version = "0.1.0"
edition = "2021"

[dependencies]
rand = "0.8.5"

Now for the game itself; a simple guessing game, where the game picks a random number from 1 to 100. The goal of the game is to guess the number, and for every try the game will tell if the guess was too high or too low or correct. The game continues until the number is guessed.

use std::io; // bring io library into scope,
             // which comes from the standard library (std)
use rand::Rng;
use std::cmp::Ordering;

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

    let secret_number = rand::thread_rng().gen_range(1..=100);

    loop {
        println!("please input your guess.");
        let mut guess = String::new(); // create mutable string, using new function

        io::stdin()
            .read_line(&mut guess)          // pass guess as a mutable reference, read
            .expect("Failed to read line"); // handle Result variant Err
                                            // expect crashes program rather than
                                            // handling the error like you should
                                            // if variant is Ok, expect will return
                                            // the number from the Ok-value

        let guess: u32 = match guess // unsigned 32-bit integer
            .trim()
            .parse() {
                Ok(num) => num,
                Err(_) => continue // ask for another guess if invalid
            };

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

Simply cargo run to run the code.

Here we can start to see some of the cool aspects of the rust language: Among others, the simple and powerful error handling with Result variants and the Cargo package mangager.

Back to Blog