Function no_std_compat::iter::repeat

1.0.0 · source ·
pub fn repeat<T>(elt: T) -> Repeat<T> 
where T: Clone,
Expand description

Creates a new iterator that endlessly repeats a single element.

The repeat() function repeats a single value over and over again.

Infinite iterators like repeat() are often used with adapters like Iterator::take(), in order to make them finite.

Use str::repeat() instead of this function if you just want to repeat a char/string nth times.

If the element type of the iterator you need does not implement Clone, or if you do not want to keep the repeated element in memory, you can instead use the repeat_with() function.

§Examples

Basic usage:

use std::iter;

// the number four 4ever:
let mut fours = iter::repeat(4);

assert_eq!(Some(4), fours.next());
assert_eq!(Some(4), fours.next());
assert_eq!(Some(4), fours.next());
assert_eq!(Some(4), fours.next());
assert_eq!(Some(4), fours.next());

// yup, still four
assert_eq!(Some(4), fours.next());

Going finite with Iterator::take():

use std::iter;

// that last example was too many fours. Let's only have four fours.
let mut four_fours = iter::repeat(4).take(4);

assert_eq!(Some(4), four_fours.next());
assert_eq!(Some(4), four_fours.next());
assert_eq!(Some(4), four_fours.next());
assert_eq!(Some(4), four_fours.next());

// ... and now we're done
assert_eq!(None, four_fours.next());