std-function
std::array::from_fn
Construct each element independently in increasing index order. The output array length comes from its type. This works with non-Copy values, such as String. Expected stdout (not executed): ["box-0", "box-1", "box-2"] Common mistake: Using [String::new(); 3] and expecting a non-Copy value to be duplicated.
Formal Syntax & Structure
rust syntaxrust
std::array::from_fn(|index| value)Working Example
Example Snippetrust
fn main() { let labels: [String; 3] = std::array::from_fn(|i| format!("box-{i}")); println!("{labels:?}");}