What is an underscore in Rust type?

Viewed 991

I am a Rust beginner, please bear with me.

As you can see in the image below, VSCode rust-analyzer inserts a type with an underscore "_". What is it?

let a: [i32; _] = [3; 5];
// this is the same as
let a: [i32; _] = [3, 3, 3, 3, 3];

the same code with type annotations [i32; _] automatically inserted by VSCode

1 Answers

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:

Related