Alex Garella
9th October 2023
Rust offers an effective way to generate random numbers through the rand crate. This blog post aims to walk you through the process of generating random numbers in Rust.
Utilizing rand
Crate:
The rand
crate in Rust is the go-to library for random number generation, known for its ease of use and flexibility.
rand
Crate:[dependencies]
rand = "0.8"
Incorporate the rand
crate into your project by adding the above lines to your Cargo.toml
file.
extern crate rand;
use rand::Rng;
fn main() {
let mut rng = rand::thread_rng();
let n: u32 = rng.gen_range(0..100);
println!("Random number: {}", n); // Output: Random number: 42
}
With just a few lines of code, generate a random number between 0 and 100.
Generating random numbers in Rust is a breeze with the rand
crate. This simple yet powerful tool is fundamental for any Rust developer looking to introduce randomness into their projects.