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.

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

Project Management 9

cargo new project_name
Create新项目(二进制)
cargo new --lib project_name
Create库项目
cargo init
在当前Directory初始化项目
cargo build
Compile项目(debug 模式)
cargo build --release
Compilerelease版本(optimize)
cargo run
Compile并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 serde
Removedependencies
cargo update
Update Cargo.lock
cargo tree
Showdependencies树
cargo tree --invert
反向Show谁dependencies某 crate

Test & Docs 5

cargo test
Run所有Test
cargo test -- --nocapture
Display println Output
cargo test test_name
Run指定Test
cargo doc --open
生成并Open文档
cargo doc --no-deps
仅生成当前 crate 文档

Code Quality 4

cargo clippy
Run Clippy lint Check
cargo clippy --fix
自动修复 Clippy warning
cargo fmt
格式化代码
cargo fmt -- --check
Check格式(CI 用)

Release & Cross-platform 6

cargo publish
release到 crates.io
cargo publish --dry-run
模拟release
cargo build --target x86_64-unknown-linux-musl
交叉Compile到 Linux
rustup target list
List可用目标平台
rustup target add x86_64-pc-windows-gnu
添加 Windows 目标
cargo install cargo-edit
Install全局命令

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