Trait SliceRandom
pub trait SliceRandom: IndexedMutRandom
Extension trait on slices, providing shuffling methods.
This trait is implemented on all [T] slice types, providing several
methods for choosing and shuffling elements. You must use this trait:
use rand::seq::SliceRandom;
let mut rng = rand::rng();
let mut bytes = "Hello, random!".to_string().into_bytes();
bytes.shuffle(&mut rng);
let str = String::from_utf8(bytes).unwrap();
println!("{}", str);
Example output (non-deterministic):
l,nmroHado !le
Required Methods
fn shuffle<R>(&mut self, rng: &mut R) where R: Rng + ?Sized,Shuffle a mutable slice in place.
For slices of length
n, complexity isO(n). The resulting permutation is picked uniformly from the set of all possible permutations.Example
use rand::seq::SliceRandom; let mut rng = rand::rng(); let mut y = [1, 2, 3, 4, 5]; println!("Unshuffled: {:?}", y); y.shuffle(&mut rng); println!("Shuffled: {:?}", y);fn partial_shuffle<R>(&mut self, rng: &mut R, amount: usize) -> (&mut [Self::Output], &mut [Self::Output]) where Self::Output: Sized, R: Rng + ?Sized,Sample
amountshuffled elementsShuffles
amountrandom elements into the end of the slice (n..wheren = self.len() - amount). The rest of the slice (..n) contains the remaining elements in a permuted but not fully shuffled order.Returns a tuple of the sampled elements (
&mut self[n..]) and the remaining elements (&mut self[..n]).This is an efficient method to select
amountelements at random from the slice, provided the slice may be mutated.For slices, complexity is
O(m)wherem = amount. Ifamount >= self.len()this is equivalent toSelf::shuffle.Example
use rand::seq::SliceRandom; let mut rng = rand::rng(); let mut y = [1, 2, 3, 4, 5]; let (shuffled, rest) = y.partial_shuffle(&mut rng, 3); assert_eq!(shuffled.len(), 3); assert_eq!(rest.len(), 2); let sampled = shuffled.to_vec(); assert_eq!(&sampled, &y[2..5]);
Implementors
impl<T> SliceRandom for [T]