Extension mixin for the Rng protocol
Contains useful methods for random number generation.
Provided methods
-
Generate a random number in a given integer range.
All range types are supported.
Example
use std::random::thread_rng; let value: i32 = thread_rng().next(0..3); assert!(value >= 0 && value < 3); let value: i32 = thread_rng().next(0..=3); assert!(value >= 0 && value <= 3); let value: i32 = thread_rng().next(..3); assert!(value < 3); let value: i32 = thread_rng().next(..=3); assert!(value <= 3); let value: i32 = thread_rng().next(3..); assert!(value >= 3); let value: i32 = thread_rng().next(..); // Any possible value of i32
Run this example -
fn next_float<T>(rng: &mut Self) -> T
Generate a random floating point number in
[0, 1)
interval.This is equivalent to sampling from StandardFloat distribution.
Example
use std::random::thread_rng; let value: f64 = thread_rng().next_float(); assert!(value >= 0.0 && value < 1.0);
Run this example -
fn shuffle<T>(rng: &mut Self, slice: &mut [T])
Permute a slice of elements in random order.
Example
use std::random::thread_rng; let values = [1, 2, 3, 4, 5]; thread_rng().shuffle(&values); for value in values { println!("{}", value); }
Run this example -
fn choice<T>(rng: &mut Self, slice: &[T]) -> T
Return a random element of the slice.
Example
use std::random::thread_rng; let value = thread_rng().choice(&["hello", "world"]); assert!(value == "hello" || value == "world");
Run this example