Random values
Now that we have a way of producing random data, how can we convert it to the type of value we want?
This is a trick question: we need to know both the range we want and the type
of distribution of this value (which is what the next
section
is all about).
The Rng
trait
For convenience, all generators automatically implement the Rng
trait,
which provides shortcuts to a few ways of generating values. This has several
convenience functions for producing uniformly distributed values:

Rng::gen
generates an unbiased (uniform) random value from a range appropriate for the type. For integers this is normally the full representable range (e.g. from0u32
tostd::u32::MAX
), for floats this is between 0 and 1, and some other types are supported, including arrays and tuples.This method is a convenience wrapper around the
Standard
distribution, as documented in the next section. 
Rng::gen_range
generates an unbiased random value with given boundslow
(inclusive) andhigh
(exclusive) 
Rng::fill
andRng::try_fill
are optimised functions for filling any byte or integer slice with random values
It also has convenience functions for producing nonuniform boolean values:
Rng::gen_bool
generates a boolean with the given probabilityRng::gen_ratio
also generates a boolean, where the probability is defined via a fraction
Finally, it has a function to sample from arbitrary distributions:
Rng::sample
samples directly from some distribution
Examples:
# #![allow(unused_variables)] #fn main() { # extern crate rand; use rand::Rng; let mut rng = rand::thread_rng(); // an unbiased integer over the entire range: let i: i32 = rng.gen(); // a uniformly distributed value between 0 and 1: let x: f64 = rng.gen(); // simulate rolling a die: let roll = rng.gen_range(1, 7); #}
Additionally, the random
function is a shortcut to Rng::gen
on the thread_rng
:
# #![allow(unused_variables)] #fn main() { if rand::random() { println!("we got lucky!"); } #}