Rust关键字分三类
因此,这些关键字不能被用作标识符(除了原始标识符)、其中包括函数、变量、参数、结构体字段、模块、crate、常量、宏、静态值、属性、类型、trait 或生命周期的名字。
严格关键字
-
as- 强制类型转换,消除特定包含项的 trait 的歧义,或者对use和extern crate语句中的项重命名 -
async- rust 2018版新增 -
await - rust 2018版新增
-
break- 立刻退出循环 -
const- 定义常量或不变裸指针(constant raw pointer) -
continue- 继续进入下一次循环迭代 -
crate- 链接(link)一个外部 crate 或一个代表宏定义的 crate 的宏变量 -
dyn- 动态分发 trait 对象,rust 2018版新增 -
else- 作为if和if let控制流结构的fallback -
enum- 定义一个枚举 -
extern- 链接一个外部 crate 、函数或变量 -
false- 布尔字面值false -
fn- 定义一个函数或 函数指针类型 (function pointer type) -
for- 遍历一个迭代器或实现一个 trait 或者指定一个更高级的生命周期 -
if- 基于条件表达式的结果分支 -
impl- 实现自有或 trait 功能 -
in-for循环语法的一部分 -
let- 绑定一个变量 -
loop- 无条件循环 -
match- 模式匹配 -
mod- 定义一个模块 -
move- 使闭包获取其所捕获项的所有权 -
mut- 表示引用、裸指针或模式绑定的可变性性 -
pub- 表示结构体字段、impl块或模块的公有可见性 -
ref- 通过引用绑定 -
return- 从函数中返回 -
Self- 实现 trait 的类型的类型别名 -
self- 表示方法本身或当前模块 -
static- 表示全局变量或在整个程序执行期间保持其生命周期 -
struct- 定义一个结构体 -
super- 表示当前模块的父模块 -
trait- 定义一个 trait -
true- 布尔字面值true -
type- 定义一个类型别名或关联类型 -
unsafe- 表示不安全的代码、函数、trait 或实现 -
use- 引入外部空间的符号 -
where- 表示一个约束类型的从句 -
while- 基于一个表达式的结果判断是否进行循环
以上可能随着最新版本的发布有所增加。
保留关键字
abstractbecomeboxdofinalmacrooverrideprivtrytypeofunsizedvirtualyield
:bell:禁止在代码中使用严格、保留关键字
弱关键字
弱关键字在特定场景下有特定含义,比如使用 union可以声明一个方法或变量。
-
unionis used to declare a union and is only a keyword when used in a union declaration. -
'staticis used for the static lifetime and cannot be used as a generic lifetime parameter// error[E0262]: invalid lifetime parameter name: `'static` fn invalid_lifetime_parameter<'static>(s: &'static str) -> &'static str { s }
原始标识符
例如,match 是关键字。如果尝试编译这个函数:
fn match(needle: &str, haystack: &str) -> bool {
haystack.contains(needle)
}
会出现如下错误:
error: expected identifier, found keyword `match`
--> src/main.rs:4:4
|
4 | fn match(needle: &str, haystack: &str) -> bool {
| ^^^^^ expected identifier, found keyword
错误提示:不能将关键字match用作函数标识符。
但是我们可以使用原始标识符将match作为函数名称使用:
fn r#match(needle: &str, haystack: &str) -> bool {
haystack.contains(needle)
}
fn main() {
assert!(r#match("foo", "foobar"));
}
此代码编译没有任何错误。
:bell: 注意 r# 前缀需同时用于函数名和调用。
原始标识符允许使用你选择的任何单词作为标识符,即使单词恰好是保留关键字。
此外,原始标识符允许你使用以不同于你的crate使用的Rust版本编写的库。比如,try 在 2015 edition 中不是关键字,而在 2018 edition 则是。所以如果如果用 2015 edition 编写的库中带有 try 函数,在 2018 edition 中调用时就需要使用原始标识符。有关版本的更多信息,请参见附录E.