Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

关键字

Rust 将关键字分为三类:

严格关键字

这些关键字只能在其正确的上下文中使用。它们不能用作以下内容的名称:

以下关键字在所有版次中都存在:

  • _
  • as
  • async
  • await
  • break
  • const
  • continue
  • crate
  • dyn
  • else
  • enum
  • extern
  • false
  • fn
  • for
  • if
  • impl
  • in
  • let
  • loop
  • match
  • mod
  • move
  • mut
  • pub
  • ref
  • return
  • self
  • Self
  • static
  • struct
  • super
  • trait
  • true
  • type
  • unsafe
  • use
  • where
  • while

2018 版次差异

以下关键字在 2018 版次中添加:

  • async
  • await
  • dyn

保留关键字

这些关键字尚未投入使用,但已为将来保留。它们与严格关键字具有相同的限制。这样做的理由是通过禁止当前程序使用这些关键字,使其与 Rust 的未来版本向前兼容。

  • abstract
  • become
  • box
  • do
  • final
  • gen
  • macro
  • override
  • priv
  • try
  • typeof
  • unsized
  • virtual
  • yield

2018 版次差异

try关键字在 2018 版次中作为保留关键字添加。

2024 版次差异

gen关键字在 2024 版次中作为保留关键字添加。

弱关键字

这些关键字仅在特定上下文中有特殊含义。例如,可以使用union这个名字声明一个变量或方法。

  • 'static
  • macro_rules
  • raw
  • safe
  • union
  • macro_rules用于创建自定义
  • union用于声明一个联合体,并且仅在联合体声明中使用时才作为关键字。
  • 'static用于静态生命周期,不能用作泛型生命周期参数循环标签

    // error[E0262]: invalid lifetime parameter name: `'static`
    fn invalid_lifetime_parameter<'static>(s: &'static str) -> &'static str { s }
    
  • safe用于函数和静态量,在外部块中有特殊含义。
  • raw用于原始借用运算符,并且仅在匹配原始借用运算符形式(例如&raw const expr&raw mut expr)时才作为关键字。

2018 版次差异

在 2015 版次中,dyn在类型位置后跟不以::<开头的路径、生命周期、问号、for关键字或左括号时是一个关键字。

从 2018 版次开始,dyn已被提升为严格关键字。