欢迎光临
我们一直在努力

附录A. Rust 关键字速查表

附录A. Rust 关键字速查表

本附录提供 Rust 语言所有关键字的完整速查表,包括当前使用的关键字、保留关键字以及特殊标识符。


当前使用的关键字

声明与定义类

关键字用途示例
fn 定义函数或方法 fn add(a: i32, b: i32) -> i32 { a + b }
let 声明变量绑定 let x = 5;
mut 声明可变变量或引用 let mut count = 0;
const 定义编译时常量 const MAX_SIZE: usize = 100;
static 定义静态变量(全局生命周期) static GLOBAL: i32 = 42;
struct 定义结构体 struct Point { x: i32, y: i32 }
enum 定义枚举类型 enum Color { Red, Green, Blue }
union 定义联合体(unsafe) union Data { i: i32, f: f32 }
type 定义类型别名 type Result<T> = std::result::Result<T, Error>;
trait 定义 Trait(接口) trait Draw { fn draw(&self); }
impl 实现方法或 Trait impl Point { fn new() -> Self { … } }

控制流类

关键字用途示例
if 条件分支 if x > 0 { println!("positive"); }
else 条件分支的否定情况 if x > 0 { … } else { … }
match 模式匹配 match value { Some(x) => x, None => 0 }
loop 无限循环 loop { break; }
while 条件循环 while count < 10 { count += 1; }
for 迭代循环 for i in 0..10 { println!("{}", i); }
break 跳出循环 loop { if done { break; } }
continue 跳过本次循环 for i in 0..10 { if i % 2 == 0 { continue; } }
return 从函数返回 fn get_value() -> i32 { return 42; }

模块与可见性类

关键字用途示例
mod 定义模块 mod utils { pub fn helper() {} }
pub 公开可见性 pub struct Point { pub x: i32 }
use 导入路径到作用域 use std::collections::HashMap;
crate 当前 crate 的根路径 use crate::utils::helper;
super 父模块路径 use super::parent_function;
self 当前模块路径或方法接收者 use self::inner_mod; 或 fn method(&self)
Self 实现类型的别名 impl Point { fn new() -> Self { … } }
extern 链接外部 crate 或声明外部函数 extern crate serde; 或 extern "C" { fn abs(x: i32) -> i32; }

所有权与生命周期类

关键字用途示例
ref 在模式中创建引用 let ref x = 5; 等价于 let x = &5;
move 强制闭包获取所有权 let closure = move || println!("{}", x);
as 类型转换或重命名导入 let x = 5 as f64; 或 use std::io::Result as IoResult;
where 泛型约束子句 fn func<T>(x: T) where T: Display { … }
dyn 动态分发 Trait 对象 let obj: Box<dyn Draw> = Box::new(circle);

异步编程类

关键字用途示例
async 定义异步函数或块 async fn fetch_data() -> String { … }
await 等待异步操作完成 let data = fetch_data().await;

Unsafe 与 FFI 类

关键字用途示例
unsafe 标记不安全代码块或函数 unsafe { *raw_ptr = 42; }

宏与属性类

关键字用途示例
macro_rules! 定义声明式宏 macro_rules! say_hello { () => { println!("Hello!"); } }

其他关键字

关键字用途示例
in for 循环的一部分 for item in collection { … }
box 堆分配(已弃用,使用 Box::new) let b = box 5; (不推荐)

保留关键字(2015 Edition)

这些关键字在 Rust 2015 Edition 中保留,但尚未使用,为未来功能预留:

关键字预留用途
abstract 可能用于抽象类型或方法
become 可能用于尾调用优化
do 可能用于循环或块
final 可能用于继承控制
macro 可能用于宏定义(已部分使用)
override 可能用于方法重写
priv 可能用于私有可见性
typeof 可能用于类型查询
unsized 可能用于动态大小类型
virtual 可能用于虚方法
yield 可能用于生成器(已在 nightly 中使用)

保留关键字(2018+ Edition)

Rust 2018 Edition 及之后新增的保留关键字:

关键字预留用途
try 可能用于错误处理(已有 try 块在 nightly)

特殊标识符

这些不是严格的关键字,但在特定上下文中有特殊含义:

生命周期标识符

标识符含义示例
'static 静态生命周期(整个程序运行期间) let s: &'static str = "hello";
'_ 匿名生命周期(编译器推断) fn func(x: &'_ str) { … }

特殊路径

标识符含义示例
$crate 宏中引用定义宏的 crate $crate::utils::helper()

特殊属性

标识符含义示例
cfg 条件编译 #[cfg(target_os = "linux")]
test 标记测试函数 #[test] fn test_add() { … }
derive 自动派生 Trait #[derive(Debug, Clone)]
allow / warn / deny Lint 控制 #[allow(dead_code)]

关键字使用注意事项

1. 原始标识符(Raw Identifiers)

如果需要使用关键字作为标识符名称,可以使用 r# 前缀:

// 使用关键字作为变量名
let r#fn = "function name";
let r#match = "match keyword";

// 使用关键字作为函数名
fn r#return() -> i32 {
42
}

// 调用
let result = r#return();

使用场景:

  • 与其他语言的 FFI 交互时,对方的函数名可能是 Rust 关键字
  • 与旧版本 Rust 代码兼容

2. 关键字的上下文敏感性

某些标识符只在特定上下文中是关键字:

// `union` 是关键字,但可以作为字段名
struct Data {
union: bool, // ❌ 编译错误
}

// 需要使用原始标识符
struct Data {
r#union: bool, // ✅ 正确
}

3. Edition 差异

不同 Edition 的关键字可能不同:

// Rust 2015: `async` 不是关键字
let async = 5; // ✅ 在 2015 Edition 中可以

// Rust 2018+: `async` 是关键字
let async = 5; // ❌ 编译错误
let r#async = 5; // ✅ 使用原始标识符


常见关键字组合模式

1. 函数定义模式

// 基本函数
fn function_name() { }

// 带参数和返回值
fn add(a: i32, b: i32) -> i32 { a + b }

// 泛型函数
fn generic<T>(value: T) -> T { value }

// 带生命周期
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { x }

// 异步函数
async fn fetch() -> String { "data".to_string() }

// Unsafe 函数
unsafe fn dangerous() { }

// 外部函数
extern "C" fn callback() { }

// 常量函数
const fn const_add(a: i32, b: i32) -> i32 { a + b }

2. 结构体与实现模式

// 定义结构体
pub struct Point {
pub x: i32,
pub y: i32,
}

// 实现方法
impl Point {
pub fn new(x: i32, y: i32) -> Self {
Self { x, y }
}

pub fn distance(&self) -> f64 {
((self.x.pow(2) + self.y.pow(2)) as f64).sqrt()
}
}

// 实现 Trait
impl std::fmt::Display for Point {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}

3. 模块与导入模式

// 定义模块
mod utils {
pub fn helper() { }

pub(crate) fn internal() { }

pub(super) fn parent_only() { }
}

// 导入
use std::collections::HashMap;
use std::io::{self, Read, Write};
use crate::utils::helper;
use super::parent_function;

// 重导出
pub use self::utils::helper;

4. 匹配与控制流模式

// match 表达式
match value {
Some(x) if x > 0 => println!("positive"),
Some(x) => println!("non-positive"),
None => println!("none"),
}

// if let
if let Some(x) = option_value {
println!("{}", x);
}

// while let
while let Some(x) = iterator.next() {
println!("{}", x);
}

// for 循环
for i in 0..10 {
if i % 2 == 0 {
continue;
}
println!("{}", i);
}

// loop 带标签
'outer: loop {
loop {
break 'outer;
}
}


快速查找索引

按功能分类

变量与常量:let, mut, const, static

类型定义:struct, enum, union, type, trait

实现:impl, fn

控制流:if, else, match, loop, while, for, break, continue, return

模块系统:mod, pub, use, crate, super, self, Self, extern

所有权:ref, move, as

泛型与约束:where, dyn

异步:async, await

安全:unsafe

宏:macro_rules!

按字母排序

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


本附录小结

  • Rust 当前有 40+ 个活跃关键字,涵盖声明、控制流、模块、所有权、异步等各个方面
  • 保留关键字 为未来功能预留,不能用作标识符
  • 使用 原始标识符 (r#keyword) 可以在必要时使用关键字作为名称
  • 不同 Edition 的关键字集合可能不同,升级时需注意
  • 理解关键字的 组合模式 有助于快速编写惯用的 Rust 代码

提示:将本速查表保存为书签,在编码时快速查阅!

赞(0)
未经允许不得转载:171主机测评 » 附录A. Rust 关键字速查表
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址