Rust Cheatsheet - Rust & Cargo Command Reference

Rust 日常开发必备 Cargo 命令都在这里了,从项目管理到交叉编译,按类别分类整理,写代码时直接复制。

Languages·51 commands·Last updated 2026-07-21
Back to Languages

项目管理 9

cargo new project_name
创建新项目(二进制)
cargo new --lib project_name
创建库项目
cargo init
在当前目录初始化项目
cargo build
编译项目(debug 模式)
cargo build --release
编译发布版本(优化)
cargo run
编译并运行
cargo run --release
以发布模式运行
cargo check
快速检查代码(不生成二进制)
cargo clean
清理 target 目录

依赖管理 6

cargo add serde
添加依赖
cargo add serde --features derive
添加依赖并启用 feature
cargo remove serde
移除依赖
cargo update
更新 Cargo.lock
cargo tree
查看依赖树
cargo tree --invert
反向查看谁依赖某 crate

测试与文档 5

cargo test
运行所有测试
cargo test -- --nocapture
显示 println 输出
cargo test test_name
运行指定测试
cargo doc --open
生成并打开文档
cargo doc --no-deps
仅生成当前 crate 文档

代码质量 4

cargo clippy
运行 Clippy lint 检查
cargo clippy --fix
自动修复 Clippy 警告
cargo fmt
格式化代码
cargo fmt -- --check
检查格式(CI 用)

发布与跨平台 6

cargo publish
发布到 crates.io
cargo publish --dry-run
模拟发布
cargo build --target x86_64-unknown-linux-musl
交叉编译到 Linux
rustup target list
列出可用目标平台
rustup target add x86_64-pc-windows-gnu
添加 Windows 目标
cargo install cargo-edit
安装全局命令

语法核心 14

let s2 = s1;
所有权转移(move 语义)
let r = &s;
不可变引用(借用)
let r = &mut s;
可变引用
fn foo<'a>(x: &'a str) -> &'a str
显式生命周期标注
fn foo(x: &str) -> &str
生命周期省略规则
match x { Some(v) => v, None => 0 }
match 模式匹配
if let Some(v) = opt {}
if let 简化匹配
while let Some(v) = iter.next() {}
while let 循环匹配
let Ok(v) = res else { return; };
let-else 语法(不匹配则返回)
Result<T, E>
结果类型(成功或错误)
Option<T>
可空类型(Some/None)
fn foo() -> Result<T, E>
返回 Result 便于错误传播
result?
错误传播运算符(出错则提前返回)
#[derive(Debug, Clone, PartialEq)]
自动派生 trait 实现

模块系统 7

use std::collections::HashMap;
导入模块
use std::io::{self, Read};
导入多个项(含重命名 self)
mod my_module;
声明子模块(从文件加载)
pub fn foo() {}
公开可见性
pub(crate) fn internal()
仅 crate 内可见
pub use crate::utils::helper;
重导出(re-export)
crate::module::func()
绝对路径引用

💡 Tips

  • cargo check 比 cargo build 快很多,日常开发用它检查编译错误。
  • cargo clippy 是官方 lint 工具,建议加入 CI 流程。
  • 发布前务必运行 cargo publish --dry-run 验证。
  • 同一时间只能有一个可变引用或多个不可变引用,二者不可共存。
  • ? 运算符只能在返回 Result 的函数中使用,自动将 Err 向上传播。
  • 生命周期省略规则适用于常见模式,复杂场景需显式标注 lifetime 参数。