Can array lengths be inferred in Rust?

后端 未结 2 1066
北恋
北恋 2020-12-11 15:16

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];

2条回答
  •  猫巷女王i
    2020-12-11 16:06

    _ 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];
    

提交回复
热议问题