Generate Random Values
Generate Random Numbers
Generates random numbers with help of the random-number generator 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.
//! This example demonstrates the basic usage of the `rand` crate for generating //! random numbers. //! //! In `Cargo.toml`, add: //! ```toml //! rand = { version = "0.9.0", features = [ "thread_rng" ] } //! ``` fn main() { // Generate a random value using the thread-local random number generator. // `random()` is a shorthand for `rng().random()` let n1: u8 = rand::random(); println!("Random u8: {}", n1); // With the "turbofish" notation: println!("Random u16: {}", rand::random::<u16>()); println!("Random u32: {}", rand::random::<u32>()); println!("Random i32: {}", rand::random::<i32>()); println!("Random float: {}", rand::random::<f64>()); // Generate a boolean if rand::random() { println!("Lucky!"); } }
Generate Random Numbers Within a Range
Generates a random value within half-open [0, 10)
range (not including 10
) with rand::Rng::gen_range
⮳ range.
use rand::Rng; /// Demonstrates generating random numbers within a specified range. fn main() { // Obtain a random number generator. let mut rng = rand::rng(); // Generate a random integer between 0 (inclusive) and 10 (exclusive). println!("Integer: {}", rng.random_range(0..10)); // Generate a random float between 0.0 (inclusive) and 10.0 (exclusive). println!("Float: {}", rng.random_range(0.0..10.0)); }
rand::distributions::uniform::Uniform
can obtain values with uniform distribution. This has the same effect, but may be faster when repeatedly generating numbers in the same range.
// Import necessary traits and structs from the `rand` crate. use rand::distr::Distribution; use rand::distr::Uniform; fn main() { // Create a random number generator. let mut rng = rand::rng(); // Create a uniform distribution over the range [1, 7). let die = Uniform::try_from(1..7).unwrap(); loop { let throw = die.sample(&mut rng); println!("Roll the die: {}", throw); if throw == 6 { break; } } }
Generate Random Numbers Within a 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 rand::distributions::Distribution::sample
⮳ with help of a random-number generator rand::Rng
⮳. The distributions available are documented here⮳. An example using the rand_distr::Normal
⮳ distribution is shown below.
//! This example demonstrates how to sample from a normal distribution. //! //! The `Normal` struct represents a normal distribution with a given mean and //! standard deviation. The `sample` method is used to draw a random sample from //! the distribution. use rand::distr::Distribution; use rand_distr::Normal; use rand_distr::NormalError; /// Sample from a normal distribution with mean 2.0 and standard deviation 3.0. fn main() -> Result<(), NormalError> { let mut rng = rand::rng(); let normal = Normal::new(2.0, 3.0)?; let v = normal.sample(&mut rng); println!("{} is from a N(2, 3) distribution", v); Ok(()) }
Generate Random Values of a Custom Type
Randomly generates a tuple (i32, bool, f64)
and variable of user defined type Point
. Implements the rand::distributions::Distribution
⮳ trait on type Point for rand::distributions::Standard
⮳ trait in order to allow random generation.
//! Demonstrates how to implement a custom distribution for the `rand` crate. use rand::Rng; use rand::distr::Distribution; use rand::distr::StandardUniform; /// A simple struct representing a point in 2D space. #[derive(Debug)] #[allow(dead_code)] struct Point { x: i32, y: i32, } // Required by: // pub fn random<T>() -> T // This implementation allows generating random `Point` instances. impl Distribution<Point> for StandardUniform { fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Point { let (x, y) = rng.random::<(i32, i32)>(); Point { x, y } } } fn main() { // Access a fast, pre-initialized generator. let mut rng = rand::rng(); // Generate a random tuple of (i32, bool, f64). let rand_tuple = rng.random::<(i32, bool, f64)>(); println!("Random tuple: {:?}", rand_tuple); // Generate a random Point using the custom distribution. let rand_point: Point = rng.random(); 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 rand::distributions::Alphanumeric
⮳ sample.
use rand::Rng; use rand::distr::Alphanumeric; /// Generate a random string of 30 alphanumeric characters. fn main() { let rand_string: String = rand::rng() .sample_iter(&Alphanumeric) // Take the first 30 characters. .take(30) .map(char::from) .collect(); println!("{}", rand_string); }
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 rand::Rng::gen_range
.
/// Generates a random password of a specified length using a predefined /// character set. fn main() { // Define the character set to choose from. const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\ abcdefghijklmnopqrstuvwxyz\ 0123456789)(*&^%$#@!~"; // Define the length of the password. const PASSWORD_LEN: usize = 30; let password: String = (0..PASSWORD_LEN) .map(|_| { let idx = rand::random_range(0..CHARSET.len()); CHARSET[idx] as char }) .collect(); println!("{:?}", password); }
fastrand
fastrand
⮳ is a simple and fast random number generator. No dependencies, non-cryptographically secure random numbers, lower complexity than rand
⮳.