Rust Cheatsheet
Quick reference for Cargo commands, error handling, serde, and daily Rust quality checks.
Cargo & Quality Commands
cargo new my-app # Create a new binary crate
cargo build --release # Build optimized release binary
cargo run # Compile and run
cargo check # Fast compile check (no binary output)
cargo test --workspace # Run all tests across the workspace
cargo fmt --all --check # Verify formatting
cargo clippy --workspace --all-targets -- -D warnings # Strict CI lint check
Handling Option & Result
use std::fs;
use std::io;
fn read_config(path: &str) -> Result<String, io::Error> {
let content = fs::read_to_string(path)?; // Propagate Err early
Ok(content)
}
let port = std::env::var("APP_PORT").unwrap_or_else(|_| "8080".to_string());
Ownership & Borrowing Summary
| Syntax | Meaning |
|---|---|
T | Transfers ownership (move) |
&T | Immutable borrow (many &T allowed at once) |
&mut T | Mutable borrow (only one &mut T at a time) |
String vs &str | Heap-owned string vs borrowed string slice |
Vec<T> vs &[T] | Owned growable array vs borrowed slice |
Serialization with serde
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct DeviceConfig {
name: String,
baud: u32,
}
Dependency & Security Checks
cargo deny --workspace check # Check licenses, advisories, and crate sources
cargo audit # Scan Cargo.lock against RustSec advisories