pub struct Choose<'a, T> { /* private fields */ }
Expand description
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§
Trait Implementations§
Source§impl<'a, T> Distribution<&'a T> for Choose<'a, T>
impl<'a, T> Distribution<&'a T> for Choose<'a, T>
Source§impl SampleString for Choose<'_, char>
Available on crate feature alloc
only.
impl SampleString for Choose<'_, char>
Available on crate feature
alloc
only.impl<'a, T: Copy> Copy for Choose<'a, T>
Auto Trait Implementations§
impl<'a, T> Freeze for Choose<'a, T>
impl<'a, T> RefUnwindSafe for Choose<'a, T>where
T: RefUnwindSafe,
impl<'a, T> Send for Choose<'a, T>where
T: Sync,
impl<'a, T> Sync for Choose<'a, T>where
T: Sync,
impl<'a, T> Unpin for Choose<'a, T>
impl<'a, T> UnwindSafe for Choose<'a, T>where
T: RefUnwindSafe,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Layout§
Note: Most layout information is completely unstable and may even differ between compilations. The only exception is types with certain repr(...)
attributes. Please see the Rust Reference's “Type Layout” chapter for details on type layout guarantees.
Size: 56 bytes