Struct Choose
pub struct Choose<'a, T> { /* private fields */ }
A distribution to uniformly sample elements of a slice
Like IndexedRandom::choose, this uniformly samples elements of a slice
without modification of the slice (so called "sampling with replacement").
This distribution object may be a little faster for repeated sampling (but
slower for small numbers of samples).
Examples
Since this is a distribution, Rng::sample_iter and
Distribution::sample_iter may be used, for example:
use rand::distr::{Distribution, slice::Choose};
let vowels = ['a', 'e', 'i', 'o', 'u'];
let vowels_dist = Choose::new(&vowels).unwrap();
// build a string of 10 vowels
let vowel_string: String = vowels_dist
.sample_iter(&mut rand::rng())
.take(10)
.collect();
println!("{}", vowel_string);
assert_eq!(vowel_string.len(), 10);
assert!(vowel_string.chars().all(|c| vowels.contains(&c)));
For a single sample, IndexedRandom::choose may be preferred:
use rand::seq::IndexedRandom;
let vowels = ['a', 'e', 'i', 'o', 'u'];
let mut rng = rand::rng();
println!("{}", vowels.choose(&mut rng).unwrap());
Implementations
impl<'a, T> Choose<'a, T>
fn new(slice: &'a [T]) -> Result<Self, Empty>Create a new
Chooseinstance which samples uniformly from the slice.Returns error
Emptyif the slice is empty.fn num_choices(&self) -> NonZeroUsizeReturns the count of choices in this distribution
Trait Implementations
impl SampleString for Choose<'_, char>
fn append_string<R: Rng + ?Sized>(&self, rng: &mut R, string: &mut String, len: usize)
impl<'a, T> Distribution<&'a T> for Choose<'a, T>
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> &'a T
impl<'a, T: Clone> Clone for Choose<'a, T>
fn clone(&self) -> Self
impl<'a, T: Copy> Copy for Choose<'a, T>
impl<'a, T: Debug> Debug for Choose<'a, T>
fn fmt(&self, f: &mut Formatter<'_>) -> Result