Iterators.
Iterators provide an abstraction for types that can be used to access their elements
one-by-one, for example in for
loop. The most common examples are ranges and collections.
for i in 0..10 {
println!("{}", i);
}
for i in &["a", "b", "c"] {
println!("{}", i);
}
Run this example
There is distinction between an iterable type and an iterator. Iterators are consumable objects that can only be used to iterate once. Iterable types are ones that can produce an iterator when needed.
Iterators can also be combined to create more complex types of iterators. See IteratorExt mixin for a reference of methods that can be used to combine iterators.
Protocols
Structs
Functions
-
fn empty<T>() -> EmptyIterator<T>
Returns an iterator that produces no elements.
Example
let range = std::iter::empty::<()>(); assert_eq!(range.next(), Option::none());
Run this example -
fn from_fn<F, T>(func: F) -> FromFnIterator<F, T>
F: Fn() -> Option<T>Wraps a function in an iterator.
Example
use std::iter::from_fn; use std::random::thread_rng; let sqrt2 = from_fn(|| -> Option<f64> { Option::some(thread_rng().next_float()) }) .map(|v: f64| -> f64 { v * 10.0 }) .filter(|v: f64| -> bool { v * v <= 2.0 }) .take(100000) .max() .unwrap(); println!("{}", sqrt2); // Prints approximately 1.4142135623730951
Run this example -
fn repeat<T>(value: T) -> RepeatIterator<T>
Returns an iterator that repeats the same value indefinitely.
Example
let range = std::iter::repeat(42); assert_eq!(range.next(), Option::some(42)); assert_eq!(range.next(), Option::some(42)); assert_eq!(range.next(), Option::some(42)); // ...
Run this example -
fn once<T>(value: T) -> OnceIterator<T>
Returns an iterator that repeats a single element exactly once.
Example
let iter = std::iter::once(42); assert_eq!(iter.next(), Option::some(42)); assert_eq!(iter.next(), Option::none());
Run this example
Types
-
Type of the element that an Iterable yields.
use std::collections::Vector; use std::iter::iterable_yield_t; let v: Vector<&[u8]> = Vector::new(); defer v.free(); v.push("Hello, world!"); let v: iterable_yield_t<Vector<&[u8]>> /* = &[u8] */ = v.iter().next().unwrap();
Run this example -
Type of the element that an Iterator yields.
Example
use std::iter::iterator_yield_t; use std::range::Range; let _: iterator_yield_t<Range<i32>>; // = i32
Run this example