Rust 关键字

1,695 阅读3分钟

Rust关键字分三类

  1. strict 严格关键字
  2. reserved保留关键字
  3. weak 弱关键字

因此,这些关键字不能被用作标识符(除了原始标识符)、其中包括函数、变量、参数、结构体字段、模块、crate、常量、宏、静态值、属性、类型、trait 或生命周期的名字。

严格关键字


  1. as - 强制类型转换,消除特定包含项的 trait 的歧义,或者对 useextern crate 语句中的项重命名

  2. async - rust 2018版新增

  3. await - rust 2018版新增

  4. break - 立刻退出循环

  5. const - 定义常量或不变裸指针(constant raw pointer)

  6. continue - 继续进入下一次循环迭代

  7. crate - 链接(link)一个外部 crate 或一个代表宏定义的 crate 的宏变量

  8. dyn - 动态分发 trait 对象,rust 2018版新增

  9. else - 作为 ifif let 控制流结构的 fallback

  10. enum - 定义一个枚举

  11. extern - 链接一个外部 crate 、函数或变量

  12. false - 布尔字面值 false

  13. fn - 定义一个函数或 函数指针类型 (function pointer type)

  14. for - 遍历一个迭代器或实现一个 trait 或者指定一个更高级的生命周期

  15. if - 基于条件表达式的结果分支

  16. impl - 实现自有或 trait 功能

  17. in - for 循环语法的一部分

  18. let - 绑定一个变量

  19. loop - 无条件循环

  20. match - 模式匹配

  21. mod - 定义一个模块

  22. move - 使闭包获取其所捕获项的所有权

  23. mut - 表示引用、裸指针或模式绑定的可变性性

  24. pub - 表示结构体字段、impl 块或模块的公有可见性

  25. ref - 通过引用绑定

  26. return - 从函数中返回

  27. Self - 实现 trait 的类型的类型别名

  28. self - 表示方法本身或当前模块

  29. static - 表示全局变量或在整个程序执行期间保持其生命周期

  30. struct - 定义一个结构体

  31. super - 表示当前模块的父模块

  32. trait - 定义一个 trait

  33. true - 布尔字面值 true

  34. type - 定义一个类型别名或关联类型

  35. unsafe - 表示不安全的代码、函数、trait 或实现

  36. use - 引入外部空间的符号

  37. where - 表示一个约束类型的从句

  38. while - 基于一个表达式的结果判断是否进行循环

以上可能随着最新版本的发布有所增加。

保留关键字


  1. abstract
  2. become
  3. box
  4. do
  5. final
  6. macro
  7. override
  8. priv
  9. try
  10. typeof
  11. unsized
  12. virtual
  13. yield

:bell:禁止在代码中使用严格、保留关键字

弱关键字


弱关键字在特定场景下有特定含义,比如使用 union可以声明一个方法或变量。

  1. union is used to declare a union and is only a keyword when used in a union declaration.

  2. 'static is 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.