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 Edition differences

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

  • async
  • await
  • dyn

保留关键字

这些关键字尚未使用,但为将来使用而保留。它们与严格关键字具有相同的限制。这样做的原因是禁止程序使用这些关键字,从而使当前程序与未来的 Rust 版本保持向前兼容。

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

2018 Edition differences

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

2024 Edition differences

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

弱关键字

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

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

    // 错误[E0262]: 无效的生存期参数名称: `'static`
    fn invalid_lifetime_parameter<'static>(s: &'static str) -> &'static str { s }
    
  • safe 用于函数和静态项,在外部块中具有含义。
  • raw 用于原始借用运算符,且仅在匹配原始借用运算符形式(如 &raw const expr&raw mut expr)时才是关键字。

2018 Edition differences

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

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