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
- Each value has exactly one owner
- When the owner goes out of scope, the value is dropped
- 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 onErr/None— use?and proper error handling in production- The borrow checker prevents data races at compile time — trust it
&is an immutable reference;&mutis mutable (one at a time)Stringowns heap data;&stris a borrowed string sliceimpl Traitin argument position vs return position both work- Use
#[derive(Debug, Clone, PartialEq)]for common trait impls let mut v: Vec<i32> = vec![]— vectors grow onpushiter()borrows,into_iter()consumes,iter_mut()mutably borrowsmatcharms must be exhaustive —_catches remaining cases
See full Rust tutorials for systems programming patterns.
← Previous
Go Cheatsheet — Complete Quick Reference (2026)
Next →
Bash Scripting Cheatsheet — Complete Quick Reference (2026)
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro