附录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定义联合体unsafeunion Data { i: i32, f: f32 }type定义类型别名type ResultT std::result::ResultT, Error;trait定义 Trait接口trait Draw { fn draw(self); }impl实现方法或 Traitimpl 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 funcT(x: T) where T: Display { ... }dyn动态分发 Trait 对象let obj: Boxdyn 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!); } }其他关键字关键字用途示例infor循环的一部分for item in collection { ... }box堆分配已弃用使用Box::newlet b box 5;(不推荐)保留关键字2015 Edition这些关键字在 Rust 2015 Edition 中保留但尚未使用为未来功能预留关键字预留用途abstract可能用于抽象类型或方法become可能用于尾调用优化do可能用于循环或块final可能用于继承控制macro可能用于宏定义已部分使用override可能用于方法重写priv可能用于私有可见性typeof可能用于类型查询unsized可能用于动态大小类型virtual可能用于虚方法yield可能用于生成器已在 nightly 中使用保留关键字2018 EditionRust 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/denyLint 控制#[allow(dead_code)]关键字使用注意事项1. 原始标识符Raw Identifiers如果需要使用关键字作为标识符名称可以使用r#前缀// 使用关键字作为变量名letr#fnfunction name;letr#matchmatch keyword;// 使用关键字作为函数名fnr#return()-i32{42}// 调用letresultr#return();使用场景与其他语言的 FFI 交互时对方的函数名可能是 Rust 关键字与旧版本 Rust 代码兼容2. 关键字的上下文敏感性某些标识符只在特定上下文中是关键字// union 是关键字但可以作为字段名structData{union:bool,// ❌ 编译错误}// 需要使用原始标识符structData{r#union:bool,// ✅ 正确}3. Edition 差异不同 Edition 的关键字可能不同// Rust 2015: async 不是关键字letasync5;// ✅ 在 2015 Edition 中可以// Rust 2018: async 是关键字letasync5;// ❌ 编译错误letr#async5;// ✅ 使用原始标识符常见关键字组合模式1. 函数定义模式// 基本函数fnfunction_name(){}// 带参数和返回值fnadd(a:i32,b:i32)-i32{ab}// 泛型函数fngenericT(value:T)-T{value}// 带生命周期fnlongesta(x:astr,y:astr)-astr{x}// 异步函数asyncfnfetch()-String{data.to_string()}// Unsafe 函数unsafefndangerous(){}// 外部函数externCfncallback(){}// 常量函数constfnconst_add(a:i32,b:i32)-i32{ab}2. 结构体与实现模式// 定义结构体pubstructPoint{pubx:i32,puby:i32,}// 实现方法implPoint{pubfnnew(x:i32,y:i32)-Self{Self{x,y}}pubfndistance(self)-f64{((self.x.pow(2)self.y.pow(2))asf64).sqrt()}}// 实现 Traitimplstd::fmt::DisplayforPoint{fnfmt(self,f:mutstd::fmt::Formatter)-std::fmt::Result{write!(f,({}, {}),self.x,self.y)}}3. 模块与导入模式// 定义模块modutils{pubfnhelper(){}pub(crate)fninternal(){}pub(super)fnparent_only(){}}// 导入usestd::collections::HashMap;usestd::io::{self,Read,Write};usecrate::utils::helper;usesuper::parent_function;// 重导出pubuseself::utils::helper;4. 匹配与控制流模式// match 表达式matchvalue{Some(x)ifx0println!(positive),Some(x)println!(non-positive),Noneprintln!(none),}// if letifletSome(x)option_value{println!({},x);}// while letwhileletSome(x)iterator.next(){println!({},x);}// for 循环foriin0..10{ifi%20{continue;}println!({},i);}// loop 带标签outer:loop{loop{breakouter;}}快速查找索引按功能分类变量与常量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 代码提示将本速查表保存为书签在编码时快速查阅