I am a Rust beginner, please bear with me.
As you can see in the image below, VS Code rust-analyzer prompts a type hint with an underscore "_" in the size part. What is it?
let a: [i32; _] = [3; 5];
// this is the same as
let a: [i32; _] = [3, 3, 3, 3, 3];
VS Code is cheating here.
When a type is expected, _
means that the compiler must infer the type. For example:
let v: [_; 5] = [3; 5];
// ^ infers type for usage
f(&v); // where f: fn(&[u8])
// the previous type will be inferred to `u8`
However, this is only possible where a type is expected. [T; _]
is not valid Rust:
let foo: [i32; _] = [1, 2];
gives
error: expected expression, found reserved identifier `_`
--> src/main.rs:2:20
|
1 | let foo: [i32; _] = [1, 2];
| --- ^ expected expression
| |
| while parsing the type for `foo`
But VS Code uses this anyway as a way to say "I don't know the value here" as while this is not valid Rust, it is a well understood concept.
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With