Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify const array in global scope in Rust?

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.

like image 794
Oleg Eterevsky Avatar asked May 22 '14 14:05

Oleg Eterevsky


People also ask

How do you declare an array in Rust?

An array is written as: let array: [i32; 3] = [4, 5, 6];

How do you use your const in Rust?

To declare a constant variable in rust, we use the const keyword followed by the name of the variable and its type. The syntax is as shown: const var_name: type = value; Note that you must explicitly specify the type of a constant variable, unlike normal variables in Rust.

Does rust have const?

Rust has two different types of constants which can be declared in any scope including global. Both require explicit type annotation: const : An unchangeable value (the common case). static : A possibly mut able variable with 'static lifetime.

Are rust arrays mutable?

In Rust, an array is immutable, which means we cannot change its elements once it is created. However, we can create a mutable array by using the mut keyword before assigning it to a variable.


2 Answers

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]; 
like image 178
Chris Morgan Avatar answered Oct 01 '22 04:10

Chris Morgan


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

const NUMBERS: &'static [i32] = &[1, 2, 3, 4, 5]; 
like image 42
Grzegorz Barański Avatar answered Oct 01 '22 04:10

Grzegorz Barański