How to Generate a 4 Digit Random Number in Rust?

Hello Friends Today, through this tutorial, I will tell you how to generate a 4-digit random number in Rust.

Here’s how to generate a 4-digit random number in Rust:

use rand::Rng;

fn main() {
let mut rng = rand::thread_rng();

// Generate a random number between 1000 and 9999 (inclusive)
let random_number: u32 = rng.gen_range(1000..=9999);

println!("Generated random 4-digit number: {}", random_number);
}

Explanation

1.`use rand::Rng;` This line imports the `Rng` trait from the `rand` crate, giving access to random number generation functionalities.
2.`let mut rng = rand::thread_rng();` This line creates a mutable random number generator using the `thread_rng` function. The `mut` keyword allows us to modify the state of the generator.
3.`let random_number: u32 = rng.gen_range(1000..=9999);` Here, we:
– Define a variable `random_number` of type `u32` (unsigned 32-bit integer) to hold the generated value.
– Call the `gen_range` method on the `rng` object. This method generates a random number within the specified range (inclusive).
– The range is defined as `1000..=9999`, ensuring the generated number has 4 digits by including both the lower and upper bounds.
4.`println!(“Generated random 4-digit number: {}”, random_number);` This line prints the generated random number to the console with a descriptive message.

Running the code..

1. Save the code as a Rust file (e.g., `random_number.rs`).
2. Compile and run the code using the Rust compiler: `rustc random_number.rs && ./random_number`
3. This will generate a random 4-digit number and print it to the console. Each time you run the code, you will get a different random number.