Function rand::random

source ·
pub fn random<T>() -> Twhere
    Standard: Distribution<T>,
Available on crate features std and std_rng only.
Expand description

Generates a random value using the thread-local random number generator.

This function is simply a shortcut for thread_rng().gen():

  • See ThreadRng for documentation of the generator and security
  • See Standard for documentation of supported types and distributions


let x = rand::random::<u8>();
println!("{}", x);

let y = rand::random::<f64>();
println!("{}", y);

if rand::random() { // generates a boolean
    println!("Better lucky than good!");

If you’re calling random() in a loop, caching the generator as in the following example can increase performance.

use rand::Rng;

let mut v = vec![1, 2, 3];

for x in v.iter_mut() {
    *x = rand::random()

// can be made faster by caching thread_rng

let mut rng = rand::thread_rng();

for x in v.iter_mut() {
    *x = rng.gen();