How to specify const array in global scope in Rust?

ArraysStaticLiteralsRust

Arrays Problem Overview


When I tried to add a const array in the global scope using this code:

static NUMBERS: [i32] = [1, 2, 3, 4, 5];

I got the following error:

error: mismatched types:
 expected `[i32]`,
    found `[i32; 5]`
(expected slice,
    found array of 5 elements) [E0308]

static NUMBERS2: [i32] = [1, 2, 3, 4, 5];
                         ^~~~~~~~~~~~~~~

The only way I found to deal with this problem is to specify the length in the type:

static NUMBERS: [i32; 5] = [1, 2, 3, 4, 5];

Is there a better way? It should be possible to create an array without manually counting its elements.

Arrays Solutions


Solution 1 - Arrays

Using [T; N] is the proper way to do it in most cases; that way there is no boxing of values at all. There is another way, though, which is also useful at times, though it is slightly less efficient (due to pointer indirection): &'static [T]. In your case:—

static NUMBERS: &'static [i32] = &[1, 2, 3, 4, 5];

Solution 2 - Arrays

You can use const for that, here is an example:

const NUMBERS: &'static [i32] = &[1, 2, 3, 4, 5];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOleg EterevskyView Question on Stackoverflow
Solution 1 - ArraysChris MorganView Answer on Stackoverflow
Solution 2 - ArraysGrzegorz BarańskiView Answer on Stackoverflow