core::iter

Function successors

1.34.0 · source
pub fn successors<T, F>(first: Option<T>, succ: F) -> Successors<T, F> 
where F: FnMut(&T) -> Option<T>,
Expand description

Creates a new iterator where each successive item is computed based on the preceding one.

The iterator starts with the given first item (if any) and calls the given FnMut(&T) -> Option<T> closure to compute each item’s successor.

use std::iter::successors;

let powers_of_10 = successors(Some(1_u16), |n| n.checked_mul(10));
assert_eq!(powers_of_10.collect::<Vec<_>>(), &[1, 10, 100, 1_000, 10_000]);