Function core::iter::repeat [] [src]

pub fn repeat<T: Clone>(elt: T) -> Repeat<T>

Creates a new iterator that endlessly repeats a single element.

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

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

Examples

Basic usage:

fn main() { 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()); }
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 take():

fn main() { 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()); }
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());