Skip to content

Rust Cheatsheet — Complete Quick Reference (2026)

DodaTech Updated 2026-06-20 4 min read

In this tutorial, you'll learn about Rust Cheatsheet. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

Rust is a systems programming language focused on memory safety, zero-cost abstractions, and fearless concurrency — achieving C-like performance without a garbage collector.

Ownership Rules

  1. Each value has exactly one owner
  2. When the owner goes out of scope, the value is dropped
  3. References never change ownership
let s1 = String::from("hello");
let s2 = s1;                         // s1 MOVED to s2 — s1 invalid
let s3 = s2.clone();                 // deep copy (heap)
let x = 10; let y = x;              // i32: Copy trait — both valid

Borrowing & References

fn calc_len(s: &String) -> usize { s.len() }       // immutable ref
fn append(s: &mut String) { s.push_str("!") }      // mutable ref

// Rules:
// - Many immutable refs (&T) OR one mutable ref (&mut T), never both
// - References must always be valid (no dangling pointers)

Lifetimes

fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() { x } else { y }
}
// 'static — lives entire program duration
let s: &'static str = "hardcoded";

Structs

struct User { name: String, age: u32 }
let u = User { name: String::from("Alice"), age: 30 };
let u2 = User { age: 25, ..u };                             // struct update

// tuple struct
struct Point(i32, i32);
let p = Point(3, 4);

// unit struct
struct Marker;

// impl block
impl User { fn greet(&self) -> String { format!("Hi, {}", self.name) } }
impl Point { fn origin() -> Self { Self(0, 0) } }

Enums & Pattern Matching

enum Result<T, E> { Ok(T), Err(E) }
enum Option<T> { Some(T), None }
enum Color { Red, Green, Blue }

fn describe(color: Color) -> &'static str {
    match color {
        Color::Red => "hot",
        Color::Green => "nature",
        _ => "other",
    }
}

if let Some(val) = option { println!("{val}") }
while let Some(val) = iter.next() { }

Traits & Generics

trait Speak { fn speak(&self) -> String; }
impl Speak for Dog { fn speak(&self) -> String { "woof".into() } }

// generics
fn largest<T: PartialOrd>(list: &[T]) -> &T { &list[0] }

// trait bounds
fn print<T: Display>(item: T) { println!("{item}") }
fn process<T>(item: T) where T: Display + Clone { }

// impl Trait (inline)
fn make_greeter() -> impl Fn(&str) -> String {
    |name| format!("Hello {name}")
}

Error Handling

// Result<T, E>
fn read_file() -> Result<String, io::Error> {
    let content = fs::read_to_string("file.txt")?;   // ? propagates error
    Ok(content)
}

// panic! for unrecoverable
panic!("something went wrong");

// custom error
#[derive(Debug)]
struct MyErr(String);
impl fmt::Display for MyErr { ... }
impl std::error::Error for MyErr {}

Cargo Commands

Command Description
cargo new project New project
cargo build Build debug
cargo build --release Build optimized
cargo run Build + run
cargo test Run tests
cargo check Type-check only (fast)
cargo clippy Lint checks
cargo fmt Format code
cargo add crate Add dependency
cargo doc --open Build docs
cargo publish Publish to crates.io

Concurrency

use std::thread;

let handle = thread::spawn(|| { 42 });
let result = handle.join().unwrap();

// message passing
use std::sync::mpsc;
let (tx, rx) = mpsc::channel();
thread::spawn(move || { tx.send(42).unwrap(); });
println!("got {}", rx.recv().unwrap());

// shared state
use std::sync::{Arc, Mutex};
let counter = Arc::new(Mutex::new(0));

Must-Know Items

  • unwrap() panics on Err/None — use ? and proper error handling in production
  • The borrow checker prevents data races at compile time — trust it
  • & is an immutable reference; &mut is mutable (one at a time)
  • String owns heap data; &str is a borrowed string slice
  • impl Trait in argument position vs return position both work
  • Use #[derive(Debug, Clone, PartialEq)] for common trait impls
  • let mut v: Vec<i32> = vec![] — vectors grow on push
  • iter() borrows, into_iter() consumes, iter_mut() mutably borrows
  • match arms must be exhaustive — _ catches remaining cases
What is ownership in Rust?

Ownership is Rust's system for memory management without a garbage collector. Each value has exactly one owner, and the value is dropped when the owner goes out of scope. Ownership can be transferred (moved) between variables, preventing double-free and use-after-free bugs at compile time.

What is the difference between a String and a &str?

String is an owned, growable UTF-8 string stored on the heap. &str (&'static str) is a borrowed reference to a string slice — it does not own the data. String can be created from &str via .to_string() or String::from(), and &str can be obtained from String via &s[..] or s.as_str().

See full Rust tutorials for systems programming patterns.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro