【发布时间】:2020-05-22 08:06:10
【问题描述】:
我是 Rust 初学者,请多多包涵。
如下图所示,VSCode rust-analyzer 插入了一个带有下划线“_”的类型。这是什么?
let a: [i32; _] = [3; 5];
// this is the same as
let a: [i32; _] = [3, 3, 3, 3, 3];
【问题讨论】:
标签: rust rust-analyzer
我是 Rust 初学者,请多多包涵。
如下图所示,VSCode rust-analyzer 插入了一个带有下划线“_”的类型。这是什么?
let a: [i32; _] = [3; 5];
// this is the same as
let a: [i32; _] = [3, 3, 3, 3, 3];
【问题讨论】:
标签: rust rust-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`
但是,这只有在需要 type 的情况下才有可能。 [T; _] 不是有效的 Rust:
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,但它是一个很好理解的概念。
另见:
【讨论】: