Initializing an array of strings in Rust

Viewed 16832

I want to create a mutable array of a fixed size. The elements are initialized later in the program. How do I initialize the array?

I tried doing this:

let mut array: [String; 126] = [String::new(); 126];

and it gives me the error:

the trait bound 'std::string::String: std::marker::Copy' is not satisfied
the trait 'std::marker::Copy' is not implemented for 'std::string::String'

how do I initialize the array with new strings?

3 Answers

There are ways that work for types without const ways to construct them, for example:

let mut a = [(); 126].map(|_| String::new());

The other answer with const EMPTY_STRING: String = String::new() is probably better for this particular case, as the documentation of the array::map method warns that this might be inefficient and consume a lot of stack space.

In nightly (as of Rust 1.57), there is also an even nicer function std::array::from_fn().

You can use (the result of) a const function, for example String::new(), to initialize an array:

const EMPTY_STRING: String = String::new();
let mut array: [String; 126] = [EMPTY_STRING; 126];
Related