Rust Cheatsheet - Rust & Cargo Command Reference
All essential Rust commands organized by use case, with 51+ entries you can copy and run directly. Find the right command fast when you need it.
Back to LanguagesProject Management 9
cargo new project_nameCreate新项目(二进制)
cargo new --lib project_nameCreate库项目
cargo init在当前Directory初始化项目
cargo buildCompile项目(debug 模式)
cargo build --releaseCompilerelease版本(optimize)
cargo runCompile并Run
cargo run --release以release模式Run
cargo check快速Check代码(不生成二进制)
cargo clean清理 target Directory
Dependencies 6
cargo add serde添加dependencies
cargo add serde --features derive添加dependencies并启用 feature
cargo remove serdeRemovedependencies
cargo updateUpdate Cargo.lock
cargo treeShowdependencies树
cargo tree --invert反向Show谁dependencies某 crate
Test & Docs 5
cargo testRun所有Test
cargo test -- --nocaptureDisplay println Output
cargo test test_nameRun指定Test
cargo doc --open生成并Open文档
cargo doc --no-deps仅生成当前 crate 文档
Code Quality 4
cargo clippyRun Clippy lint Check
cargo clippy --fix自动修复 Clippy warning
cargo fmt格式化代码
cargo fmt -- --checkCheck格式(CI 用)
Release & Cross-platform 6
cargo publishrelease到 crates.io
cargo publish --dry-run模拟release
cargo build --target x86_64-unknown-linux-musl交叉Compile到 Linux
rustup target listList可用目标平台
rustup target add x86_64-pc-windows-gnu添加 Windows 目标
cargo install cargo-editInstall全局命令
Core Syntax 14
let s2 = s1;所有权转移(move 语义)
let r = &s;不可变引用(借用)
let r = &mut s;可变引用
fn foo<'a>(x: &'a str) -> &'a str显式生命periodic标注
fn foo(x: &str) -> &str生命periodic省略规则
match x { Some(v) => v, None => 0 }match 模式Match
if let Some(v) = opt {}if let 简化Match
while let Some(v) = iter.next() {}while let loopMatch
let Ok(v) = res else { return; };let-else 语法(不Match则返回)
Result<T, E>结果type(成功或错误)
Option<T>可空type(Some/None)
fn foo() -> Result<T, E>返回 Result 便于错误传播
result?错误传播运算符(出错则提前返回)
#[derive(Debug, Clone, PartialEq)]自动派生 trait 实现
Module System 7
use std::collections::HashMap;Importmodule
use std::io::{self, Read};Import多个项(含Rename self)
mod my_module;Declare子module(从File加载)
pub fn foo() {}公开可见性
pub(crate) fn internal()仅 crate 内可见
pub use crate::utils::helper;重Export(re-export)
crate::module::func()绝对路径引用
💡 Tips
- cargo check 比 cargo build 快很多,日常开发用它CheckCompile错误。
- cargo clippy 是官方 lint 工具,建议加入 CI 流程。
- release前务必Run cargo publish --dry-run 验证。
- 同一时间只能有一个可变引用或多个不可变引用,二者不可共存。
- ? 运算符只能在返回 Result 的function中使用,自动将 Err 向上传播。
- 生命periodic省略规则for常见模式,复杂场景需显式标注 lifetime Options。
Official References
Commands are compiled from the official docs below. Click to verify the latest usage.
Maintained by LaoHand
Publicly updated on Jul 21, 2026, continuously proofread against official docs.
Found an error? Report it
Wrong command or description? Open an issue to help us fix it.
Found an error? Report it