首页 > 解决方案 > Rust 类型中的下划线是什么?

问题描述

我是 Rust 初学者,请多多包涵。

如下图所示,VSCode rust-analyzer插入了一个带有下划线“_”的类型。它是什么?

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

具有类型注释的相同代码 [i32;  _] 由 VSCode 自动插入

标签: rustrust-analyzer

解决方案


VS Code 在这里作弊。

当需要类型时,_意味着编译器必须推断类型。例如:

let v: [_; 5] = [3; 5];
    //  ^ infers type for usage

f(&v); // where f: fn(&[u8])
       // the previous type will be inferred to `u8`

但是,这仅在需要类型时才有可能。[T; _]不是有效的锈:

let foo: [i32; _] = [1, 2];

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`

但是 VS Code 无论如何都使用它来表达“我不知道这里的价值”,因为虽然这不是有效的 Rust,但它是一个很好理解的概念。

也可以看看:


推荐阅读