[−][src]Function rand::seq::sample_iter
pub fn sample_iter<T, I, R: ?Sized>(
rng: &mut R,
iterable: I,
amount: usize
) -> Result<Vec<T>, Vec<T>> where
I: IntoIterator<Item = T>,
R: Rng,
Randomly sample amount
elements from a finite iterator.
The following can be returned:
Ok
:Vec
ofamount
non-repeating randomly sampled elements. The order is not random.Err
:Vec
of all the elements fromiterable
in sequential order. This happens when the length ofiterable
was less thanamount
. This is considered an error since exactlyamount
elements is typically expected.
This implementation uses O(len(iterable))
time and O(amount)
memory.
Example
use rand::{thread_rng, seq}; let mut rng = thread_rng(); let sample = seq::sample_iter(&mut rng, 1..100, 5).unwrap(); println!("{:?}", sample);