Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does rust not know the size of a const array literal at compile time?

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]`
like image 370
Marcus Gosselin Avatar asked Nov 29 '25 17:11

Marcus Gosselin


1 Answers

[&'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?

  1. 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).
  2. 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.

like image 187
Elias Holzmann Avatar answered Dec 02 '25 05:12

Elias Holzmann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!