rust - Rust 类型中的下划线是什么?
问题描述
我是 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,但它是一个很好理解的概念。
也可以看看:
推荐阅读
- openshift - 在 minishift 上持久安装 gogs
- c - 使用 double 调用函数后删除所有小数
- python - 如何从没有索引的数据框中选择值
- android - Android - EditText 在全屏风景中失去焦点
- c# - EF Core 共享事务在这里是一个好的解决方案,还是一个糟糕的设计?
- python - 如何使用 python 向 JSON 子级添加唯一 ID?
- r - 在 for 循环中运行函数并将返回的数据帧添加到 R 中的列表中
- apache-spark - 将 unix_timestamp 转换为 spark 中的普通时间戳(以秒为单位)
- python-3.x - Python脚本在目录中搜索特定文件类型,然后将它们的内容附加在一起
- memory-management - 虚拟内存效应和分页与分段之间的关系