Generate Random Values
Generate random numbers
Generates random numbers with help of random-number
generator rand::Rng
obtained via rand::rng
. Each thread has an
initialized generator. Integers are uniformly distributed over the range of the
type, and floating point numbers are uniformly distributed from 0 up to but not
including 1.
use rand::Rng; fn main() { let mut rng = rand::thread_rng(); let random_number: u32 = rng.gen(); println!("Random number: {}", random_number); }
Generate random numbers within a range
Generates a random value within half-open [0, 10)
range (not including 10
) with [Rng::gen_range
].
use rand::Rng; fn main() { let mut rng = rand::rng(); println!("Integer: {}", rng.gen_range(0..10)); println!("Float: {}", rng.gen_range(0.0..10.0)); }
[Uniform
] can obtain values with uniform distribution.
This has the same effect, but may be faster when repeatedly generating numbers
in the same range.
use rand::Rng; use rand_distr::{Distribution, Uniform}; fn main() { let mut rng = rand::rng(); let die = Uniform::new_inclusive(1, 6) .expect("Failed to create uniform distribution: invalid range"); loop { let throw = die.sample(&mut rng); println!("Roll the die: {}", throw); if throw == 6 { break; } } }
Generate random numbers with given distribution
By default, random numbers in the rand
crate have
uniform distribution. The rand_distr
crate provides
other kinds of distributions. To use them, you instantiate
a distribution, then sample from that distribution using
Distribution::sample
with help of a random-number
generator rand::Rng
.
The distributions available are documented here.
An example using the Normal
distribution is shown below.
use rand::Rng; use rand_distr::{Distribution, LogNormal, Normal}; fn main() { let mut rng = rand::rng(); let normal = Normal::new(2.0, 3.0) .expect("Failed to create normal distribution"); let log_normal = LogNormal::new(1.0, 0.5) .expect("Failed to create log-normal distribution"); let v = normal.sample(&mut rng); println!("{} is from a N(2, 9) distribution", v); let v = log_normal.sample(&mut rng); println!("{} is from an ln N(1, 0.25) distribution", v); }
Generate random values of a custom type
Randomly generates a tuple (i32, bool, f64)
and variable of user defined type Point
.
Implements the [Distribution
] trait on type Point for [Standard
] in order to allow random generation.
use rand::Rng; #[derive(Debug)] struct Point { x: i32, y: i32, } impl Point { fn random<R: Rng>(rng: &mut R) -> Self { Point { x: rng.random(), y: rng.random(), } } } fn main() { let mut rng = rand::rng(); let rand_tuple = rng.random::<(i32, bool, f64)>(); let rand_point = Point::random(&mut rng); println!("Random tuple: {:?}", rand_tuple); println!("Random Point: {:?}", rand_point); }
Create random passwords from a set of alphanumeric characters
Randomly generates a string of given length ASCII characters in the range A-Z, a-z, 0-9
, with Alphanumeric
sample.
use rand::Rng; fn main() { const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz\ 0123456789"; const PASSWORD_LEN: usize = 30; let mut rng = rand::rng(); let password: String = (0..PASSWORD_LEN) .map(|_| { let idx = rng.random_range(0..CHARSET.len()); CHARSET[idx] as char }) .collect(); println!("{}", password); }
Create random passwords from a set of user-defined characters
Randomly generates a string of given length ASCII characters with custom
user-defined bytestring, with gen_range
.
use rand::Rng; const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz\ 0123456789)(*&^%$#@!~"; const PASSWORD_LEN: usize = 30; fn main() { let mut rng = rand::rng(); let password: String = (0..PASSWORD_LEN) .map(|_| { let idx = rng.gen_range(0..CHARSET.len()); char::from(CHARSET[idx]) }) .collect(); println!("{:?}", password); }