std-method
Vec::resize_with
When growing, call the generator for each new slot. When shrinking, drop trailing elements without invoking the generator. No Clone bound is needed. Expected stdout (not executed): [99, 100, 101, 102] Common mistake: Expecting the generator to run for elements already in the vector.
Formal Syntax & Structure
rust syntaxrust
pub fn resize_with<F>(&mut self, new_len: usize, f: F) where F: FnMut() -> TWorking Example
Example Snippetrust
fn main() { let mut ids = vec![99]; let mut next = 100; ids.resize_with(4, || { let id = next; next += 1; id }); println!("{ids:?}");}