Expand description
Utilities for random number generation
Rand provides utilities to generate random numbers, to convert them to useful types and distributions, and some randomness-related algorithms.
§Quick Start
// The prelude import enables methods we use below, specifically
// Rng::random, Rng::sample, SliceRandom::shuffle and IndexedRandom::choose.
use rand::prelude::*;
// Get an RNG:
let mut rng = rand::rng();
// Try printing a random unicode code point (probably a bad idea)!
println!("char: '{}'", rng.random::<char>());
// Try printing a random alphanumeric value instead!
println!("alpha: '{}'", rng.sample(rand::distr::Alphanumeric) as char);
// Generate and shuffle a sequence:
let mut nums: Vec<i32> = (1..100).collect();
nums.shuffle(&mut rng);
// And take a random pick (yes, we didn't need to shuffle first!):
let _ = nums.choose(&mut rng);
§The Book
For the user guide and further documentation, please read The Rust Rand Book.
Modules§
- Generating random samples from probability distributions
- Convenience re-export of common members
- Random number generators and adapters
- Sequence-related functionality
Traits§
- A marker trait used to indicate that an
RngCore
implementation is supposed to be cryptographically secure. - Types which may be filled with random data
- User-level interface for RNGs
- Implementation-level interface for RNGs
- A random number generator that can be explicitly seeded.
- A marker trait used to indicate that a
TryRngCore
implementation is supposed to be cryptographically secure. - A potentially fallible version of
RngCore
.
Functions§
- fill
std
andstd_rng
andos_rng
Fill any type implementingFill
with random data - random
std
andstd_rng
andos_rng
Generate a random value using the thread-local random number generator. - random_
bool std
andstd_rng
andos_rng
Return a bool with a probabilityp
of being true. - random_
iter std
andstd_rng
andos_rng
Return an iterator overrandom()
variates - random_
range std
andstd_rng
andos_rng
Generate a random value in the given range using the thread-local random number generator. - random_
ratio std
andstd_rng
andos_rng
Return a bool with a probability ofnumerator/denominator
of being true. - rng
std
andstd_rng
andos_rng
Access a fast, pre-initialized generator - thread_
rng Deprecated std
andstd_rng
andos_rng
Access the thread-local generator