Guessing Game
On chapter 2 of the book 'The Rust Programming Language (2nd Edition)', specifically titled 'Programming a guessing game' it has me setting up a new cargo project similar to before as follows:
cargo new guessing_game
cd guessing_game
It has then set up the following files:
- src/main.rs the main code file of the project:
fn main() {
println!("Hello, world!");
}
Seem to contain a basic hello world program as a starting point.
Then we have:
Cargo.toml
[package]
name = "guessing_game"
version = "0.1.0"
edition = "2024"
[dependencies]
Everything is self explanatory there.
In the overall code for this chapter I have the following, changing the file main.rs mentioned above:
use rand::Rng;
use std::cmp::Ordering;
use std::io;
fn main() {
println!("Guess the number!");
let secret_number = rand::rng().random_range(1..=100);
// println!("The secret number is: {secret_number}");
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(num) => num,
Err(_) => continue,
};
println!("You guessed: {guess}");
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}
What I learned in this chapter
- Brought in an external crate (
rand
) to generate a secret number. - Used
io::stdin().read_line(&mut guess)
to get and store user input. - Converted the input string into a number with
trim().parse()
and amatch
to skip bad input. - Employed a
loop
plusmatch guess.cmp(&secret_number)
for the guessing logic. - Reinforced ownership and borrowing by passing
&mut guess
and&secret_number
. - Printed messages with
println!
and Rust’s formatting placeholders.
Title: Guessing Game
Author: Jamie Cropley
Date published: 18/05/2025
URL: https://www.rust.foo/blog/guessinggame/
Accessed on: 02/06/2025
Website: Rust Foo