# Trait rand::seq::IteratorRandom [−][src]

```
pub trait IteratorRandom: Iterator + Sized {
fn choose<R>(self, rng: &mut R) -> Option<Self::Item>
```

where

R: Rng + ?Sized,
{ ... }
fn choose_multiple_fill<R>(

self,

rng: &mut R,

buf: &mut [Self::Item]

) -> usize

where

R: Rng + ?Sized,
{ ... }
fn choose_multiple<R>(self, rng: &mut R, amount: usize) -> Vec<Self::Item>

where

R: Rng + ?Sized,
{ ... }
}

## Expand description

Extension trait on iterators, providing random sampling methods.

This trait is implemented on all sized iterators, providing methods for
choosing one or more elements. You must `use`

this trait:

```
use rand::seq::IteratorRandom;
fn main() {
let mut rng = rand::thread_rng();
let faces = "😀😎😐😕😠😢";
println!("I am {}!", faces.chars().choose(&mut rng).unwrap());
}
```

Example output (non-deterministic):

`I am 😀!`

## Provided methods

Choose one element at random from the iterator.

Returns `None`

if and only if the iterator is empty.

This method uses `Iterator::size_hint`

for optimisation. With an
accurate hint and where `Iterator::nth`

is a constant-time operation
this method can offer `O(1)`

performance. Where no size hint is
available, complexity is `O(n)`

where `n`

is the iterator length.
Partial hints (where `lower > 0`

) also improve performance.

For slices, prefer `SliceRandom::choose`

which guarantees `O(1)`

performance.

Collects values at random from the iterator into a supplied buffer until that buffer is filled.

Although the elements are selected randomly, the order of elements in the buffer is neither stable nor fully random. If random ordering is desired, shuffle the result.

Returns the number of elements added to the buffer. This equals the length of the buffer unless the iterator contains insufficient elements, in which case this equals the number of elements available.

Complexity is `O(n)`

where `n`

is the length of the iterator.
For slices, prefer `SliceRandom::choose_multiple`

.

Collects `amount`

values at random from the iterator into a vector.

This is equivalent to `choose_multiple_fill`

except for the result type.

Although the elements are selected randomly, the order of elements in the buffer is neither stable nor fully random. If random ordering is desired, shuffle the result.

The length of the returned vector equals `amount`

unless the iterator
contains insufficient elements, in which case it equals the number of
elements available.

Complexity is `O(n)`

where `n`

is the length of the iterator.
For slices, prefer `SliceRandom::choose_multiple`

.