[&'static str]
is a slice of &'static str
elements. A slice is kind of like an array, but has runtime-defined length – and you can't really hold something with a length that is unknown at compile-time inside a variable as this variable must have a defined length.
As you already found out, you have two possible solutions:
1.
const strings: [&'static str; 3] = ["Element 1", "Element 2", "Element 3"];
This constructs a variable of the type "array of &'static str
, length 3". The length of the array is part of the type information.
2.
const strings: &[&'static str] = &["Element 1", "Element 2", "Element 3"];
In this version, strings
only holds a reference to a slice holding the elements. How does this reference work, and how is it constructed?
- References to slices are actually not normal references, but fat pointers consisting of a pointer to the first element of the slice combined with the slice length (see for example this for more information about fat pointers in Rust).
- Here, Rust first builds an array with length 3 and then borrows it, thereby becoming a
&[&'static str]
. (As you might have noticed, borrowing actually gets you a &[&'static str; 3]
– Rust implicitly converts this from "reference to array" to "reference to slice".)
Which solution should you use?
In most cases, it doesn't really matter. Personally, I'd use version 1 and convert to a slice when needed, thereby preventing the (small) overhead of the fat pointer if possible.