Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing an array of strings in Rust

Tags:

arrays

rust

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?

like image 517
user3161500 Avatar asked May 25 '17 17:05

user3161500


1 Answers

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.

like image 62
E_net4 stands with Ukraine Avatar answered Nov 12 '22 16:11

E_net4 stands with Ukraine