rand::random - Rust
Description: API documentation for the Rust `random` fn in crate `rand`.
Keywords: rust, rustlang, rust-lang, random

# Function rand::random [−] [src]

    pub fn random<T: Rand>() -> T

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

`random()` can generate various types of random things, and so may require type hinting to generate the specific type you want.

This function uses the thread local random number generator. This means that if you're calling `random()` in a loop, caching the generator can increase performance. An example is shown below.

# Examples

    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!");
    }

Caching the thread local random number generator:

    use rand::Rng;

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

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

    // would be faster as

    let mut rng = rand::thread_rng();

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

# Help

## Keyboard Shortcuts

?
  Show this help dialog
S
  Focus the search field
⇤
  Move up in search results
⇥
  Move down in search results
⏎
  Go to active search result
+
  Collapse/expand all sections

## Search Tricks

Prefix searches with a type followed by a colon (e.g. `fn:`) to restrict the search to a given type.

Accepted types are: `fn`, `mod`, `struct`, `enum`, `trait`, `type`, `macro`, and `const`.

Search functions by type signature (e.g. `vec -> usize` or `* -> vec`)