Iterator

Trait Iterator 

1.6.0 · Source
pub trait Iterator {
    type Item;

    // Required method
    fn next(&mut self) -> Option<Self::Item>;

    // Provided methods
    fn size_hint(&self) -> (usize, Option<usize>) { ... }
    fn map<B, F>(self, f: F) -> Map<Self, F>
       where Self: Sized,
             F: FnMut(Self::Item) -> B { ... }
    fn cloned<'a, T>(self) -> Cloned<Self>
       where T: Clone + 'a,
             Self: Sized + Iterator<Item = &'a T> { ... }
}
Available on crate feature ferrocene_certified only.
Expand description

A trait for dealing with iterators.

This is the main iterator trait. For more about the concept of iterators generally, please see the module-level documentation. In particular, you may want to know how to implement Iterator.

Required Associated Types§

1.0.0 · Source

type Item

The type of the elements being iterated over.

Required Methods§

1.0.0 · Source

fn next(&mut self) -> Option<Self::Item>

Advances the iterator and returns the next value.

Returns None when iteration is finished. Individual iterator implementations may choose to resume iteration, and so calling next() again may or may not eventually start returning Some(Item) again at some point.

§Examples
let a = [1, 2, 3];

let mut iter = a.into_iter();

// A call to next() returns the next value...
assert_eq!(Some(1), iter.next());
assert_eq!(Some(2), iter.next());
assert_eq!(Some(3), iter.next());

// ... and then None once it's over.
assert_eq!(None, iter.next());

// More calls may or may not return `None`. Here, they always will.
assert_eq!(None, iter.next());
assert_eq!(None, iter.next());

Provided Methods§

1.0.0 · Source

fn size_hint(&self) -> (usize, Option<usize>)

Returns the bounds on the remaining length of the iterator.

Specifically, size_hint() returns a tuple where the first element is the lower bound, and the second element is the upper bound.

The second half of the tuple that is returned is an Option<usize>. A None here means that either there is no known upper bound, or the upper bound is larger than usize.

§Implementation notes

It is not enforced that an iterator implementation yields the declared number of elements. A buggy iterator may yield less than the lower bound or more than the upper bound of elements.

size_hint() is primarily intended to be used for optimizations such as reserving space for the elements of the iterator, but must not be trusted to e.g., omit bounds checks in unsafe code. An incorrect implementation of size_hint() should not lead to memory safety violations.

That said, the implementation should provide a correct estimation, because otherwise it would be a violation of the trait’s protocol.

The default implementation returns (0, None) which is correct for any iterator.

§Examples

Basic usage:

let a = [1, 2, 3];
let mut iter = a.iter();

assert_eq!((3, Some(3)), iter.size_hint());
let _ = iter.next();
assert_eq!((2, Some(2)), iter.size_hint());

A more complex example:

// The even numbers in the range of zero to nine.
let iter = (0..10).filter(|x| x % 2 == 0);

// We might iterate from zero to ten times. Knowing that it's five
// exactly wouldn't be possible without executing filter().
assert_eq!((0, Some(10)), iter.size_hint());

// Let's add five more numbers with chain()
let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);

// now both bounds are increased by five
assert_eq!((5, Some(15)), iter.size_hint());

Returning None for an upper bound:

// an infinite iterator has no upper bound
// and the maximum possible lower bound
let iter = 0..;

assert_eq!((usize::MAX, None), iter.size_hint());
1.0.0 · Source

fn map<B, F>(self, f: F) -> Map<Self, F>
where Self: Sized, F: FnMut(Self::Item) -> B,

Takes a closure and creates an iterator which calls that closure on each element.

map() transforms one iterator into another, by means of its argument: something that implements FnMut. It produces a new iterator which calls this closure on each element of the original iterator.

If you are good at thinking in types, you can think of map() like this: If you have an iterator that gives you elements of some type A, and you want an iterator of some other type B, you can use map(), passing a closure that takes an A and returns a B.

map() is conceptually similar to a for loop. However, as map() is lazy, it is best used when you’re already working with other iterators. If you’re doing some sort of looping for a side effect, it’s considered more idiomatic to use for than map().

§Examples

Basic usage:

let a = [1, 2, 3];

let mut iter = a.iter().map(|x| 2 * x);

assert_eq!(iter.next(), Some(2));
assert_eq!(iter.next(), Some(4));
assert_eq!(iter.next(), Some(6));
assert_eq!(iter.next(), None);

If you’re doing some sort of side effect, prefer for to map():

// don't do this:
(0..5).map(|x| println!("{x}"));

// it won't even execute, as it is lazy. Rust will warn you about this.

// Instead, use a for-loop:
for x in 0..5 {
    println!("{x}");
}
1.0.0 · Source

fn cloned<'a, T>(self) -> Cloned<Self>
where T: Clone + 'a, Self: Sized + Iterator<Item = &'a T>,

Creates an iterator which clones all of its elements.

This is useful when you have an iterator over &T, but you need an iterator over T.

There is no guarantee whatsoever about the clone method actually being called or optimized away. So code should not depend on either.

§Examples

Basic usage:

let a = [1, 2, 3];

let v_cloned: Vec<_> = a.iter().cloned().collect();

// cloned is the same as .map(|&x| x), for integers
let v_map: Vec<_> = a.iter().map(|&x| x).collect();

assert_eq!(v_cloned, [1, 2, 3]);
assert_eq!(v_map, [1, 2, 3]);

To get the best performance, try to clone late:

let a = [vec![0_u8, 1, 2], vec![3, 4], vec![23]];
// don't do this:
let slower: Vec<_> = a.iter().cloned().filter(|s| s.len() == 1).collect();
assert_eq!(&[vec![23]], &slower[..]);
// instead call `cloned` late
let faster: Vec<_> = a.iter().filter(|s| s.len() == 1).cloned().collect();
assert_eq!(&[vec![23]], &faster[..]);

Implementors§

1.1.0 · Source§

impl<'a, I, T> Iterator for Cloned<I>
where I: Iterator<Item = &'a T>, T: Clone + 'a,

Source§

type Item = T

1.0.0 · Source§

impl<'a, T> Iterator for Iter<'a, T>

1.0.0 · Source§

impl<'a, T> Iterator for IterMut<'a, T>

1.0.0 · Source§

impl<A> Iterator for core::option::IntoIter<A>

Source§

type Item = A

1.0.0 · Source§

impl<B, I: Iterator, F> Iterator for Map<I, F>
where F: FnMut(I::Item) -> B,

Source§

type Item = B

1.0.0 · Source§

impl<I: Iterator + ?Sized> Iterator for &mut I

Implements Iterator for mutable references to iterators, such as those produced by [Iterator::by_ref].

This implementation passes all method calls on to the original iterator.

Source§

type Item = <I as Iterator>::Item

1.80.0 · Source§

impl<T> !Iterator for [T]

1.40.0 · Source§

impl<T, const N: usize> Iterator for core::array::IntoIter<T, N>

Source§

type Item = T