I'm still new to rust, so I'm not sure if this is phrased correctly, but essentially, I'm looking for a reason why rust doesnt understand that this array has, and only ever will have 3 elements at compile time? I can simply add a 3 to the type, and it works. or i change it to borrowed &[&'static str] (which i assume majorly changes how it compiled), and it will also work. What am I missing?
const strings: [&'static str] = ["Element 1", "Element 2", "Element 3"];
// the size for values of type `[&'static str]` cannot be known at compilation time
// the trait `Sized` is not implemented for `[&'static str]`
[&'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?
&[&'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".)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.
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