我是 Rust 初学者,请多多包涵。
如下图所示,VSCode rust-analyzer插入了一个带有下划线“_”的类型。它是什么?
let a: [i32; _] = [3; 5];
// this is the same as
let a: [i32; _] = [3, 3, 3, 3, 3];
我是 Rust 初学者,请多多包涵。
如下图所示,VSCode rust-analyzer插入了一个带有下划线“_”的类型。它是什么?
let a: [i32; _] = [3; 5];
// this is the same as
let a: [i32; _] = [3, 3, 3, 3, 3];
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,但它是一个很好理解的概念。
也可以看看: