97

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.

2
  • 2
    If you are looking for some discussion about why Rust was designed this way, see this forum thread. Commented Dec 29, 2016 at 15:50
  • 6
    If you want it to be const, best to write like: const NUMBERS: [i32; 5] = [1, 2, 3, 4, 5]; Commented Sep 9, 2017 at 17:34

2 Answers 2

105

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];
Sign up to request clarification or add additional context in comments.

5 Comments

If you're looking for a way to do this with strings: stackoverflow.com/a/32383866/1349450
clippy tells me that "statics have by default a 'static lifetime"
@RobertoLeinardi: from your comment, I suspect you may be misunderstanding something. What Clippy will be saying there is that if you elide lifetimes in statics, it’ll infer 'static—and that is something new since I first wrote the answer, you couldn’t elide lifetimes in statics back then. But 'static is the only lifetime possible in statics, since they’re being stored in the read-only memory of the binary and must necessarily live forever. But concerning this question and answer, lifetimes are a bit of a red herring; the key thing is the difference between an array and a slice.
And how can I create a big static matrix? example in c++11 I can write static constexpr int my_arr[64][64]{ {13,44...},{..}.... }
@gekomad: type composition is much saner in Rust: arrays are [T; N] and values are […], so you can make them multidimensional with straightforward nesting, like static MY_ARR: [[i32; 64]; 64] = [[13, 44, …], […], …];. (Also, your comment is barely related to the question here, please ask new questions for things like that—or search, it’s probably answered already.)
18

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

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

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.