Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an underscore in rust-analyzer's type hints for array size?

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

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

like image 496
shin Avatar asked Sep 14 '25 11:09

shin


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:

  • What does it mean to instantiate a Rust generic with an underscore?
  • What is Vec<_>?
  • Can array lengths be inferred in Rust?
like image 187
mcarton Avatar answered Sep 17 '25 06:09

mcarton