The rand crate provides us plenty of ways to generate random numbers. Here are a few examples:
Generate a random integer that fits in an i8
let random_i8: i8 = rand::random();
Generate random floating point that fits in an f32
let random_f32: f32 = rand::random();
Generate a random boolean
We can even ask it to generate a true
or false
randomly.
let random_bool: bool = rand::random();
Generate a random whole number in a range
For this we need to load the rand::Rng
use rand::Rng;
let random_number = rand::thread_rng().gen_range(1..=100);
Dependency
examples/generate-random-numbers/Cargo.toml
[package]
name = "generate-random-numbers"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rand = "0.8.5"
Code
examples/generate-random-numbers/src/main.rs
use rand::Rng;
fn main() {
let random_i8: i8 = rand::random();
println!("random_i8: {random_i8}");
let random_f32: f32 = rand::random();
println!("random_f32: {random_f32}");
let random_bool: bool = rand::random();
println!("random_bool: {random_bool}");
let random_number = rand::thread_rng().gen_range(1..=100);
println!("random_number: {random_number}");
}
Running the code
$ cargo run -q
random_i8: 47
random_f32: 0.69342864
random_bool: false
random_number: 54
$ cargo run -q
random_i8: 46
random_f32: 0.063155234
random_bool: false
random_number: 31