附录
本附录汇总了常用的 Rust 命令、常见编译错误和推荐的学习资源。
Cargo 命令速查
Section titled “Cargo 命令速查”| 命令 | 说明 |
|---|---|
cargo new <name> | 创建新的二进制项目 |
cargo new --lib <name> | 创建新的库项目 |
cargo init | 在当前目录初始化项目 |
cargo build | 编译项目(debug 模式) |
cargo build --release | 编译项目(release 模式,有优化) |
cargo run | 编译并运行 |
cargo run -- <args> | 编译并运行,传递参数 |
cargo check | 检查代码能否编译(不生成可执行文件) |
cargo clean | 删除 target 目录 |
| 命令 | 说明 |
|---|---|
cargo test | 运行所有测试 |
cargo test <name> | 运行名称包含 <name> 的测试 |
cargo test -- --nocapture | 显示测试中的 println 输出 |
cargo test -- --test-threads=1 | 单线程运行测试 |
cargo test --doc | 只运行文档测试 |
| 命令 | 说明 |
|---|---|
cargo doc | 生成文档 |
cargo doc --open | 生成并在浏览器中打开文档 |
cargo doc --no-deps | 只生成当前 crate 的文档 |
| 命令 | 说明 |
|---|---|
cargo add <crate> | 添加依赖 |
cargo add <crate>@<version> | 添加指定版本的依赖 |
cargo remove <crate> | 移除依赖 |
cargo update | 更新所有依赖 |
cargo update -p <crate> | 更新指定依赖 |
cargo tree | 显示依赖树 |
| 命令 | 说明 |
|---|---|
cargo fmt | 格式化代码 |
cargo clippy | 代码 lint 检查 |
cargo fix | 自动修复警告 |
cargo publish | 发布到 crates.io |
cargo install <crate> | 安装二进制 crate |
Rustup 命令
Section titled “Rustup 命令”| 命令 | 说明 |
|---|---|
rustup update | 更新 Rust |
rustup default stable | 设置默认工具链为 stable |
rustup default nightly | 设置默认工具链为 nightly |
rustup component add rustfmt | 安装 rustfmt |
rustup component add clippy | 安装 clippy |
rustup doc | 打开本地文档 |
常见编译错误
Section titled “常见编译错误”E0382:使用已移动的值
Section titled “E0382:使用已移动的值”let s1 = String::from("hello");let s2 = s1;println!("{}", s1); // 错误!s1 已被移动解决方法:
- 使用
clone()复制 - 使用引用而不是移动
E0499:多个可变借用
Section titled “E0499:多个可变借用”let mut s = String::from("hello");let r1 = &mut s;let r2 = &mut s; // 错误!解决方法:确保同一时间只有一个可变借用
E0502:同时存在可变和不可变借用
Section titled “E0502:同时存在可变和不可变借用”let mut s = String::from("hello");let r1 = &s;let r2 = &mut s; // 错误!println!("{}", r1);解决方法:确保在可变借用之前不可变借用已结束
E0106:缺少生命周期标注
Section titled “E0106:缺少生命周期标注”fn longest(x: &str, y: &str) -> &str { // 错误! if x.len() > y.len() { x } else { y }}解决方法:添加生命周期标注 fn longest<'a>(x: &'a str, y: &'a str) -> &'a str
E0277:trait bound 不满足
Section titled “E0277:trait bound 不满足”fn print<T>(value: T) { println!("{}", value); // 错误!T 没有实现 Display}解决方法:添加 trait bound fn print<T: std::fmt::Display>(value: T)
E0308:类型不匹配
Section titled “E0308:类型不匹配”let x: i32 = "hello"; // 错误!解决方法:使用正确的类型或进行转换
E0425:找不到名称
Section titled “E0425:找不到名称”fn main() { println!("{}", x); // 错误!x 未定义}解决方法:确保变量已定义且在作用域内
E0433:找不到模块
Section titled “E0433:找不到模块”use foo::bar; // 错误!模块不存在解决方法:确保模块存在且可见
#[derive(Debug)] // 调试输出#[derive(Clone)] // 克隆#[derive(Copy)] // 复制(要求 Clone)#[derive(PartialEq, Eq)] // 相等比较#[derive(PartialOrd, Ord)] // 排序比较#[derive(Hash)] // 哈希#[derive(Default)] // 默认值#[test] // 标记为测试函数#[ignore] // 忽略测试#[should_panic] // 期望 panic#[cfg(test)] // 只在测试时编译#[cfg(target_os = "linux")]#[cfg(feature = "some_feature")]#[cfg(debug_assertions)]其他常用属性
Section titled “其他常用属性”#[allow(dead_code)] // 允许未使用代码#[allow(unused_variables)] // 允许未使用变量#[must_use] // 返回值必须使用#[deprecated] // 标记为废弃#[inline] // 内联提示常用标准库类型
Section titled “常用标准库类型”| 类型 | 说明 |
|---|---|
Box<T> | 堆分配 |
Rc<T> | 引用计数(单线程) |
Arc<T> | 原子引用计数(多线程) |
RefCell<T> | 内部可变性(单线程) |
Mutex<T> | 互斥锁(多线程) |
RwLock<T> | 读写锁(多线程) |
| 类型 | 说明 |
|---|---|
Vec<T> | 动态数组 |
VecDeque<T> | 双端队列 |
LinkedList<T> | 双向链表 |
HashMap<K, V> | 哈希表 |
BTreeMap<K, V> | 有序映射 |
HashSet<T> | 哈希集合 |
BTreeSet<T> | 有序集合 |
BinaryHeap<T> | 优先队列 |
| 类型 | 说明 |
|---|---|
String | 可变字符串(堆分配) |
&str | 字符串切片 |
OsString | 操作系统字符串 |
CString | C 字符串 |
推荐学习资源
Section titled “推荐学习资源”| 资源 | 链接 | 说明 |
|---|---|---|
| The Rust Programming Language | doc.rust-lang.org/book | 官方入门书籍 |
| Rust By Example | doc.rust-lang.org/rust-by-example | 通过示例学习 |
| Rust Reference | doc.rust-lang.org/reference | 语言参考手册 |
| 标准库文档 | doc.rust-lang.org/std | API 文档 |
| Rustlings | github.com/rust-lang/rustlings | 小练习集合 |
| 资源 | 链接 | 说明 |
|---|---|---|
| Rust 语言圣经 | course.rs | 全面的中文教程 |
| Rust 程序设计语言 | kaisery.github.io/trpl-zh-cn | 官方书籍中文版 |
| 通过例子学 Rust | rustwiki.org/rust-by-example | 中文示例教程 |
| 资源 | 链接 | 说明 |
|---|---|---|
| The Rustonomicon | doc.rust-lang.org/nomicon | Unsafe Rust |
| Async Book | rust-lang.github.io/async-book | 异步编程 |
| Rust API Guidelines | rust-lang.github.io/api-guidelines | API 设计指南 |
| 项目 | 说明 |
|---|---|
| 命令行工具 | 文件处理、系统工具 |
| Web 服务 | 使用 Actix-web 或 Axum |
| WebAssembly | Rust + WASM |
| 嵌入式开发 | 无标准库 Rust |
| 游戏开发 | 使用 Bevy 或 Amethyst |
常用第三方库
Section titled “常用第三方库”| 库 | 用途 |
|---|---|
serde | 序列化/反序列化 |
tokio | 异步运行时 |
reqwest | HTTP 客户端 |
axum / actix-web | Web 框架 |
clap | 命令行解析 |
tracing | 日志和追踪 |
anyhow / thiserror | 错误处理 |
regex | 正则表达式 |
chrono | 日期时间 |
rand | 随机数 |
struct RequestBuilder { url: String, method: String, body: Option<String>,}
impl RequestBuilder { fn new(url: &str) -> Self { RequestBuilder { url: url.to_string(), method: String::from("GET"), body: None, } }
fn method(mut self, method: &str) -> Self { self.method = method.to_string(); self }
fn body(mut self, body: &str) -> Self { self.body = Some(body.to_string()); self }
fn build(self) -> Request { Request { url: self.url, method: self.method, body: self.body, } }}
// 使用let request = RequestBuilder::new("https://example.com") .method("POST") .body("{}") .build();struct UserId(u64);struct OrderId(u64);
// 即使底层类型相同,也不能混用fn get_order(order_id: OrderId) -> Order { ... }类型状态模式
Section titled “类型状态模式”struct Draft;struct Published;
struct Post<State> { content: String, _state: std::marker::PhantomData<State>,}
impl Post<Draft> { fn publish(self) -> Post<Published> { Post { content: self.content, _state: std::marker::PhantomData, } }}恭喜你完成了 Rust 入门教程!接下来你可以:
- 实践项目 - 用 Rust 构建自己的项目
- 深入学习 - 阅读 The Rustonomicon 学习 unsafe Rust
- 异步编程 - 学习 async/await 和 Tokio
- 加入社区 - 参与 Rust 社区,贡献开源项目
祝你 Rust 学习之旅愉快!