Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can array lengths be inferred in Rust?

Tags:

rust

I can do this:

let a: [f32; 3] = [0.0, 1.0, 2.0];

But why doesn't this work?

let a: [f32; _] = [0.0, 1.0, 2.0];

It seems to me that the length is redundant and trivial to infer. Is there a way to avoid having to specify it explicitly? (And without having to append f32 to all the literals.)

like image 523
Timmmm Avatar asked Oct 18 '16 12:10

Timmmm


People also ask

How do you find the length of an array in Rust?

The length of an array is the number of elements present in the array. We use the len() function to obtain this value.

Does rust have arrays?

Arrays are collections of same-type-data values stored in contiguous memory locations. In Rust, arrays are created using square brackets [] and their size needs to be known at compile time. An array whose size is not defined is called a slice.

Are arrays copy rust?

As far as I know all arrays are copied on move.

How do you declare an array in Rust?

The below-given surtaxes can be used to declare and initialize an array in Rust: Syntax1: let variable_name = [value_1,value_2,value_3]; Syntax2: let variable_name:[dataType;array_size] = [value_1,value_2,value_3]; Syntax3: let variable_name:[dataType;array_size] = [default_value_for_elements,array_size];


Video Answer


2 Answers

_ can only be used in two contexts: in patterns, to match a value to ignore, and as a placeholder for a type. In array types, the length is not a type, but an expression, and _ cannot be used in expressions.

What you can do, though, is append f32 to only one of the literals and omit the type completely. Since all the items of an array must have the same type, the compiler will infer the correct element type for the array.

let a = [0.0f32, 1.0, 2.0];
like image 187
Francis Gagné Avatar answered Oct 09 '22 18:10

Francis Gagné


Since 1.39 it's possible using a simple macro

macro_rules! arr {
    ($id: ident $name: ident: [$ty: ty; _] = $value: expr) => {
        $id $name: [$ty; $value.len()] = $value;
    }
}

Usage

arr!(static BYTES: [u8; _] = *b"foo");
arr!(let floats: [f32; _] = [0., 1.]);
like image 26
miedzinski Avatar answered Oct 09 '22 17:10

miedzinski