Is it possible to determine the length of an array in Rust?

I can do it:

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

But why does this not work?

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

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

+7
rust
source share
1 answer

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

However, you can add f32 only one of the literals and completely omit the type. Since all elements of the 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]; 
+19
source share

All Articles