What it is
rand is Rust's random number generation crate, covering fast general-purpose generators, cryptographically secure sources and distribution sampling.
rng() gives a thread-local, automatically seeded generator. Distributions cover uniform ranges, sampling and shuffling; separate crates provide cryptographic sources.
Installation
cargo add randGetting started
The smallest useful thing you can do with it, and what each part means.
use rand::prelude::*;
let mut rng = rand::rng();
let roll: u8 = rng.random_range(1..=6);
let chance: f64 = rng.random(); // 0.0..1.0
let flip: bool = rng.random_bool(0.3); // true 30% of the time
let mut deck: Vec<u8> = (1..=52).collect();
deck.shuffle(&mut rng);
let winner = entries.choose(&mut rng);
let sample: Vec<_> = entries.choose_multiple(&mut rng, 5).collect();Advanced usage
Where the library earns its place over a simpler alternative.
use rand::SeedableRng;
use rand_chacha::ChaCha8Rng;
// Deterministic: same seed, same sequence — essential for tests
// and reproducible simulations.
let mut rng = ChaCha8Rng::seed_from_u64(42);
let value: u32 = rng.random();
// Security-sensitive values must not come from a general-purpose PRNG.
use rand::rngs::OsRng;
let mut token = [0u8; 32];
OsRng.fill_bytes(&mut token); // suitable for session tokens and keysErrors and fixes
The failures you are most likely to hit, and what actually resolves them.
- no method named gen_range
- Renamed to random_range in 0.9, and thread_rng to rng. Check the crate version against the example.
- Tests fail intermittently
- Randomness leaked into an assertion. Seed a deterministic generator for tests.
Best practices
- Use OsRng or getrandom for tokens, keys and anything an attacker should not predict.
- Seed a ChaCha generator explicitly when a test or simulation must be reproducible.
- Create the generator once outside a loop; constructing it per iteration is wasteful.
- Check the version — the 0.8 and 0.9 APIs differ in several method names.
Background
Why it exists, and what it was reacting to.
Random generation is not in Rust's standard library, so rand is the ecosystem's answer — carefully separating the fast generator you want for simulations from the secure one you need for tokens.
