std/random
Random numbers from the platform CSPRNG: arc4random on macOS, getentropy on Linux, BCryptGenRandom on Windows. Nothing to seed, and nothing to replay: for a reproducible stream (simulations, property tests), use std/rng.
from "std/random" import { Random }For key material (secrets, salts, nonces, tokens) use Random.bytes(n): n bytes as a byte string, the form Hex.encode, Base64.urlEncode and std/crypto take.
from "std/random" import { Random }
from "std/hex" import { Hex }
fn main() {
let token = Hex.encode(Random.bytes(16)) // 32 hex digits
print(token.len)
}API reference
std/random has one implementation per target (darwin, linux, windows); the resolver picks the one for the target you build for.
Random
pub struct RandomRandom namespace — Random.int/range/float/bool/bytes/... (platform RNG).
Random.bool
fn Random.bool(): booltrue or false with equal probability.
Random.bytes
fn Random.bytes(n: i64): stringn cryptographically secure random bytes (the OS CSPRNG), as a byte string: the representation std's crypto APIs take keys, salts and nonces in (Hex.encode, Base64.urlEncode, Crypto.aesGcmEncrypt). Never fails; if the OS entropy source is unavailable the process exits rather than return predictable bytes.
Random.fillRaw
fn Random.fillRaw(buf: *u8, n: i64): voidFill buf with n random bytes, as bytes does: the raw form for a fixed array a caller already holds. buf must point at n writable bytes.
Random.float
fn Random.float(): f64A random float in [0.0, 1.0).
Random.floatRange
fn Random.floatRange(min: f64, max: f64): f64A random float in [min, max).
Random.int
fn Random.int(max: i64): i64A random integer in [0, max). max must be positive.
Random.range
fn Random.range(min: i64, max: i64): i64A random integer in [min, max], both ends inclusive.
Random.shuffleI64
fn Random.shuffleI64(v: &mut Vec<i64>, n: i64): voidShuffle the first n elements of v in place (Fisher-Yates). Pass v.len() for all.
Random.u32
fn Random.u32(): u32A random u32 in [0, 2^32).