Rust, How to generate a Random Number

Mike Code
Jul 2, 2024

--

First we need to add a crate named rand to our project:

In cargo.toml file:

[dependencies]
rand = "0.8"

Back to main.rs file:

use rand::Rng;

fn main() {
let mut rng = rand::thread_rng();
let a = rng.gen_range(0..=100);
println!("{}", a)
}

We call thread_rng funcion from rand to create a random number generator.

We call gen_range method on this generator ,and pass a range into this method , we pass 0..=100 , means it will generate a integer number between 0 and 100 (include 0 and 100 ) (If we not add = before 100 , then it will not include 100).

--

--