std-function
std::iter::successors — generate from the previous value
Begin with an optional seed and compute the next item from the current item. None ends the sequence permanently. checked arithmetic is useful for stopping on overflow. Expected stdout (not executed): [3, 6, 12, 24] Common mistake: Assuming the first emitted value is the result of the closure rather than the seed.
Formal Syntax & Structure
rust syntaxrust
pub fn successors<T, F>(first: Option<T>, succ: F) -> Successors<T, F> where F: FnMut(&T) -> Option<T>Working Example
Example Snippetrust
fn main() { let values: Vec<_> = std::iter::successors(Some(3_u32), |n| n.checked_mul(2)).take(4).collect(); println!("{values:?}");}