Tutorial: Random Number - Guessing Game in Rust ๐Ÿฆ€๐Ÿ”ข

Hello everyone and welcome back to my blog. Today I will show you how to code a "Number guessing game" using Rust.

By the end of this tutorial, you'll not only have a fun challenging game but also:

  • You'll learn how to generate random numbers for user-guessing

  • You'll learn the basics like loops and input in Rust

Don't forget you can find all the code on my GitHub profile, there will be a link for this project at the end of this article.

Code the Game

Open your favorite code editor, type in the terminal cargo new your-project-name and let's start!

Firstly, we need to import the standard library for input use std::io::stdin;, as we will need the user to input a number. Then, inside the main() we're going to create a loop and we'll name it: outer_loop , this is going to be a looping structure. Let's also declare a variable: let _number: u32 = 10; with a value of 10. This is the value that the user should guess. Finally, we're asking the user to pick a number: println!("Pick a number (1 to 15) >>>");

Note*: You may be thinking that this is a random number guessing game but we just gave* _numbera static number... Wait for it! We'll change it to a random number in a bit ๐Ÿค“.

So far we have:

fn main() {

    '_outer_loop: loop {

        let _number: u32 = 10;

        println!("Pick a number (1 to 15) >>>");
    }

But, as we mentioned above, it'd be more interesting to generate a random number. So the user will guess a new number each time they run our game.

Let's continue coding...

After showing the message Pick a number (1 to 15) >>> we need to store the user's number. So, we're going to have another loop and declare a new mutable variable that's going to contain the new empty string. We also want to pass a reference where we're going to store the string, and that's why we've imported it above the standard input library. The standard input is going to read the line .

        let mut line = String::new();
        let _input = stdin().read_line(&mut line);

Time to define our guess. ๐Ÿ˜Š

let guess: Option = input.ok().mapor(None, || line.trim().parse().ok());

In the above line of code, the ok() means that the reader is at the end of the line of the input the user entered. After this we have mapor: this is going to return the default value or apply functions to a value.

So we're going to take the line and we're going to trim it and parse that string in order to be an integer value (line.trim().parse().ok() ) so we can compare between the user's guess and the predefined number so the data types can be compatible for comparison.

Now, we can continue with matching the _guess. (And this is why needed the Option.)

match _guess{
            None => println!("enter a number..."),
            Some(n) if n == _number => {
                println!("Bravo! You guessed it!");
                break '_outer_loop;
            }
            .
            .
            .
        }
  • If the input is None, we're going to print a line that says enter a number, and if some number is entered, then we're going to compare between the user's input and the number that's predefined (which is still 10, but wait for it...).

  • If the user guessed the correct number, then we're going to print a line that says Bravo, you guessed it!. And we're going to break out of the loop. That's why we defined above the _outer_loop.

  • If the user's input is less than the number that's predefined, we're going to print Too low, and if it's higher, we're going to print Too high and if anything else, we're going to throw an error and the loop will continue.

            Some(n) if n < _number => println!("Too low"),
            Some(n) if n > _number => println!("Too high"),
            Some(_) => println!("Error!")

You can now run the program with cargo run but every time you play the game the _number will be 10. Let's fix that. ๐Ÿ‘‡

Random Number Generator

The first thing we need is to import the random range dependency. We'll need to go to cargo.toml and include this rand = "0.8.3" in [dependencies].

[dependencies]
rand = "0.8.3"

And in main.rs we'll include use rand::Rng;

Now, instead of having this predefined number 10, we're going to create a dynamic one.

// let _number: u32 = 10;
let _number: i32 = rand::thread_rng().gen_range(1..=15)

This _number will be of integer 32 instead of unassigned 32. Note:*If you have defined your variablei32, then you will need to define theOptionalsoi32, and vice versa*. Now this integer has access to thread_rng inside the random package that gen_range from 1 to 15.

Let's run the program...

Run It

Use cargo run to run the program.

Conclusion

That was our simple rust game. Feel free to experiment with rand, integer and unsigned numbers.

Check the code here.

Happy Rust Coding! ๐Ÿคž๐Ÿฆ€


๐Ÿ‘‹ Hello, I'm Eleftheria, Community Manager, developer, public speaker, and content creator.

๐Ÿฅฐ If you liked this article, consider sharing it.

๐Ÿ”— All links | X | LinkedIn

8
Subscribe to my newsletter

Read articles from Eleftheria Batsou directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Eleftheria Batsou
Eleftheria Batsou

Hi there ๐Ÿ™†โ€โ™€๏ธ, I'm Eleftheria, Community Manager with a coding background and a passion for UX. Do you have any questions? Don't hesitate to contact me. I can talk about front-end development, design, job hunting/freelancing/internships.