Trait IndexedRandom

Source
pub trait IndexedRandom: Index<usize> {
    // Required method
    fn len(&self) -> usize;

    // Provided methods
    fn is_empty(&self) -> bool { ... }
    fn choose<R>(&self, rng: &mut R) -> Option<&Self::Output>
       where R: Rng + ?Sized { ... }
    fn choose_multiple_array<R, const N: usize>(
        &self,
        rng: &mut R,
    ) -> Option<[Self::Output; N]>
       where Self::Output: Clone + Sized,
             R: Rng + ?Sized { ... }
}
Expand description

Extension trait on indexable lists, providing random sampling methods.

This trait is implemented on [T] slice types. Other types supporting [std::ops::Index<usize>] may implement this (only Self::len must be specified).

Required Methods§

Source

fn len(&self) -> usize

The length

Provided Methods§

Source

fn is_empty(&self) -> bool

True when the length is zero

Source

fn choose<R>(&self, rng: &mut R) -> Option<&Self::Output>
where R: Rng + ?Sized,

Uniformly sample one element

Returns a reference to one uniformly-sampled random element of the slice, or None if the slice is empty.

For slices, complexity is O(1).

§Example
use rand::seq::IndexedRandom;

let choices = [1, 2, 4, 8, 16, 32];
let mut rng = rand::rng();
println!("{:?}", choices.choose(&mut rng));
assert_eq!(choices[..0].choose(&mut rng), None);
Source

fn choose_multiple_array<R, const N: usize>( &self, rng: &mut R, ) -> Option<[Self::Output; N]>
where Self::Output: Clone + Sized, R: Rng + ?Sized,

Uniformly sample a fixed-size array of distinct elements from self

Chooses N elements from the slice at random, without repetition, and in random order.

For slices, complexity is the same as index::sample_array.

§Example
use rand::seq::IndexedRandom;

let mut rng = &mut rand::rng();
let sample = "Hello, audience!".as_bytes();

let a: [u8; 3] = sample.choose_multiple_array(&mut rng).unwrap();

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementations on Foreign Types§

Source§

impl<T> IndexedRandom for [T]

Source§

fn len(&self) -> usize

Implementors§