std-method

slice::fill_with

Call a closure for each element to generate replacement values. This is useful when each position needs fresh state rather than a cloned value. Expected stdout (not executed): ["item-1", "item-2", "item-3"] Common mistake: Expecting the closure to receive an index parameter automatically.

Formal Syntax & Structure

rust syntaxrust
slice.fill_with(|| new_value)

Working Example

Example Snippetrust
fn main() {    let mut labels = [String::new(), String::new(), String::new()];    let mut i = 0;    labels.fill_with(|| { i += 1; format!("item-{i}") });    println!("{labels:?}");}
Rust Reference