Skip to content

rand

Developer UtilitiesUtilitiesRust

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 rand

Getting started

The smallest useful thing you can do with it, and what each part means.

Values, ranges and shuffling
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();
rand::rng() is thread-local and seeded from the OS, so it needs no setup. Note that the 0.9 API renamed several of these methods — older tutorials use thread_rng and gen_range.

Advanced usage

Where the library earns its place over a simpler alternative.

Reproducibility and cryptographic randomness
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 keys
This distinction matters. The default generator is fast and statistically good but not designed to resist an attacker predicting future output — use OsRng or getrandom for anything security-related.

Errors 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.