Rust Language Cheat Sheet

Quick reference guide for Rust: Ownership, borrowing, pattern matching, Option/Result, structs, enums, and Cargo commands.

Languages
rust
systems
memory-safety

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:

  1. Each value in Rust has an owner.
  2. There can only be one owner at a time.
  3. When the owner goes out of scope, the value is dropped.
  4. You can have either one mutable reference (&mut T) OR any number of immutable references (&T).
rust
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.

rust
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>.

Table
Type / MethodPurposeCode 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);
? operatorPropagate Err early or unwrap Ok valuelet val = query_db()?
.unwrap_or(default)Safely fallback if None or Errlet name = user.name.unwrap_or("Guest".into());
if letConcise match for single variantif let Some(val) = opt { println!("{}", val); }

Structs & Traits

rust
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

Table
CommandPurpose / Action
cargo new app_nameCreate new binary crate project
cargo checkQuickly analyze code for compile errors without building binaries
cargo runCompile and execute application binary
cargo testExecute unit and integration tests
cargo build --releaseCompile optimized production binary in target/release/
cargo clippyRun linter for idiomatic Rust code suggestions
cargo fmtFormat 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 borrow x as mutable because it is also borrowed as immutable.

[!TIP] Use cargo check during iterative development; it is significantly faster than cargo build because it skips binary code generation.