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?
At the moment, initialization of arrays is still a bit quirky.
In particular, having Default
would have been useful here, but it's only implemented for arrays up to 32:
let array: [String; 32] = Default::default();
Any number over that will fail to compile because, while Rust 1.47 now implements some traits over a generic size for array types, Default
is yet not one of them. These 32 implementations of Default
were "sort-of" added manually.
We can overcome that with alternative container types, such as Vec
. The vec!
macro will let you clone a string as many times as you wish to fill in the new vector:
let mut array: Vec<String> = vec![String::new(); 126];
But of course, depending on your use case, you might also consider going lazy and only collecting the final outcomes using the Iterator API.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With