Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a static const Vec<String> [duplicate]

Tags:

rust

I am trying to initialize a Vec<String> with some settings that can be reused over my code.

I am using const left: Vec<String> = vec![... but this doesn't work:

error[E0308]: mismatched types
  --> names-generator.rs:2:27
   |
2  | const left: Vec<String> = vec![
   |                           ^ expected slice, found array of 93 elements
   |
   = note: expected type `Box<[std::string::String]>`
   = note:    found type `Box<[&str; 93]>`
   = note: this error originates in a macro outside of the current crate

What is the recommended way of doing something like this?

like image 328
simao Avatar asked Mar 13 '17 12:03

simao


1 Answers

Do you want it to be mutable? Do the values have to be Strings? If the answer is "no" to both, you can use an array of string slices ([&str; N]) instead of a Vec<String>:

const LEFT: [&'static str; 3] = ["Hello", "World", "!"];
// or
const LEFT: &'static [&'static str] = &["Hello", "World", "!"];

consts are basically copied wherever they are used, so the second form may be preferable depending on the size of the array.

like image 77
glebm Avatar answered Oct 23 '22 18:10

glebm