Rust Language Cheat Sheet
Quick reference guide for Rust: Ownership, borrowing, pattern matching, Option/Result, structs, enums, and Cargo commands.
Rust is a systems programming language focused on memory safety, concurrency, and high performance without a garbage collector.
Ownership & Borrowing Rules
Rust enforces strict memory management at compile time through ownership rules:
- Each value in Rust has an owner.
- There can only be one owner at a time.
- When the owner goes out of scope, the value is dropped.
- You can have either one mutable reference (
&mut T) OR any number of immutable references (&T).
fn main() {
let s1 = String::from("hello"); // s1 owns the String
// Move ownership
let s2 = s1; // s1 is no longer valid!
// Immutable borrow (reference)
let len = calculate_length(&s2);
// Mutable borrow
let mut s3 = String::from("world");
append_text(&mut s3);
println!("Length: {}, Text: {}", len, s3);
}
fn calculate_length(s: &String) -> usize {
s.len()
}
fn append_text(s: &mut String) {
s.push_str("!");
}
Pattern Matching & Enums
Pattern matching via match and if let provides exhaustive error-free control flow.
enum Status {
Active,
Inactive(String), // Variant with data
Pending { retries: u32 },
}
fn handle_status(status: Status) {
match status {
Status::Active => println!("System is active"),
Status::Inactive(reason) => println!("Inactive due to: {}", reason),
Status::Pending { retries } if retries > 5 => println!("Pending: max retries reached"),
Status::Pending { retries } => println!("Pending: retry {}", retries),
}
}
`Option` and `Result` Error Handling
Rust avoids null by using Option<T> and Result<T, E>.
| Type / Method | Purpose | Code Snippet |
|---|---|---|
Option<T> | Value presence or absence (Some(T) / None) | let x: Option<i32> = Some(5); |
Result<T, E> | Operability success or failure (Ok(T) / Err(E)) | let res: Result<i32, String> = Ok(10); |
? operator | Propagate Err early or unwrap Ok value | let val = query_db()? |
.unwrap_or(default) | Safely fallback if None or Err | let name = user.name.unwrap_or("Guest".into()); |
if let | Concise match for single variant | if let Some(val) = opt { println!("{}", val); } |
Structs & Traits
struct User {
username: String,
active: bool,
}
// Trait definition (similar to Interface)
trait Summarizable {
fn summary(&self) -> String;
}
impl Summarizable for User {
fn summary(&self) -> String {
format!("User {} (Active: {})", self.username, self.active)
}
}
Essential `cargo` Tool Commands
| Command | Purpose / Action |
|---|---|
cargo new app_name | Create new binary crate project |
cargo check | Quickly analyze code for compile errors without building binaries |
cargo run | Compile and execute application binary |
cargo test | Execute unit and integration tests |
cargo build --release | Compile optimized production binary in target/release/ |
cargo clippy | Run linter for idiomatic Rust code suggestions |
cargo fmt | Format Rust source code using rustfmt |
Common Pitfalls & Tips
[!WARNING] Attempting to create a mutable reference (
&mut x) while immutable references (&x) are active causes a compile error: cannot borrowxas mutable because it is also borrowed as immutable.
[!TIP] Use
cargo checkduring iterative development; it is significantly faster thancargo buildbecause it skips binary code generation.