Rust Cheatsheet

Rust Cheatsheet
let x = 5;

Immutable variable binding

Basics
let mut x = 5;

Mutable variable binding

Basics
const MAX: u32 = 100;

Compile-time constant

Basics
let x: i32 = 10;

Explicit type annotation

Basics
i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize

Integer types (signed/unsigned)

Basics
f32 f64

Floating point types

Basics
let s = String::from("hello");

Heap-allocated string

Basics
let s: &str = "hello";

String slice (borrowed reference)

Basics
let arr = [1, 2, 3];

Fixed-size array

Basics
let tup: (i32, f64, &str) = (1, 2.0, "hi");

Tuple with mixed types

Basics
if condition { ... } else if other { ... } else { ... }

If/else (expression, not statement)

Basics
for item in &vec { ... }

For loop over iterator

Basics
loop { break; }

Infinite loop with explicit break

Basics
while condition { ... }

While loop

Basics
println!("x = {x}, y = {}", y);

Print with formatting macros

Basics
let s2 = s1;

Move ownership (s1 is invalid after)

Ownership
let s2 = s1.clone();

Deep copy (both remain valid)

Ownership
fn take(s: String) { ... }

Function takes ownership of arg

Ownership
fn borrow(s: &String) { ... }

Immutable borrow (reference)

Ownership
fn mutate(s: &mut String) { ... }

Mutable borrow

Ownership
let r = &x;

Create immutable reference

Ownership
let r = &mut x;

Create mutable reference

Ownership
'a

Lifetime annotation (generic lifetime)

Ownership
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str

Function with lifetime parameters

Ownership
struct User { name: String, age: u32, }

Struct definition

Structs & Enums
let u = User { name: String::from("A"), age: 30 };

Struct instantiation

Structs & Enums
impl User { fn new(name: &str) -> Self { ... } }

Method implementation block

Structs & Enums
struct Point(f64, f64);

Tuple struct

Structs & Enums
enum Color { Red, Green, Blue, Rgb(u8, u8, u8), }

Enum with variants (some with data)

Structs & Enums
enum Option<T> { Some(T), None }

Option type (nullable value)

Structs & Enums
enum Result<T, E> { Ok(T), Err(E) }

Result type (success or error)

Structs & Enums
match value { Pattern => expr, _ => default, }

Pattern matching (must be exhaustive)

Structs & Enums
if let Some(x) = optional { ... }

Destructure single pattern

Structs & Enums
#[derive(Debug, Clone, PartialEq)]

Auto-derive common traits

Structs & Enums
trait Summary { fn summarize(&self) -> String; }

Trait definition

Traits
impl Summary for Article { fn summarize(&self) -> String { ... } }

Implement trait for type

Traits
fn notify(item: &impl Summary)

Trait bound (impl syntax)

Traits
fn notify<T: Summary + Display>(item: &T)

Multiple trait bounds

Traits
fn returns() -> impl Summary

Return type implementing trait

Traits
dyn Trait

Dynamic dispatch (trait object)

Traits
Box<dyn Trait>

Heap-allocated trait object

Traits
let f = File::open("f.txt")?;

Propagate error with ? operator

Error Handling
unwrap()

Panic on Err/None (use in tests only)

Error Handling
expect("msg")

Panic with custom message on Err/None

Error Handling
unwrap_or(default)

Return default on Err/None

Error Handling
unwrap_or_else(|| compute())

Return computed default on Err/None

Error Handling
match result { Ok(val) => ..., Err(e) => ..., }

Handle Result with match

Error Handling
map_err(|e| MyError::from(e))

Transform error type

Error Handling
panic!("critical error")

Unrecoverable error (abort)

Error Handling
let v: Vec<i32> = Vec::new();

Create empty vector

Collections
let v = vec![1, 2, 3];

Create vector with values (macro)

Collections
v.push(4);

Add element to vector

Collections
v.pop();

Remove and return last element

Collections
v.iter().map(|x| x * 2).collect::<Vec<_>>()

Transform with iterator chain

Collections
v.iter().filter(|x| **x > 2).collect::<Vec<_>>()

Filter with iterator

Collections
let mut map = HashMap::new(); map.insert("key", value);

Create and populate HashMap

Collections
map.get("key")

Get value from HashMap (returns Option)

Collections
map.entry("key").or_insert(0);

Insert if key doesn't exist

Collections
let set: HashSet<i32> = HashSet::new();

Create HashSet (unique values)

Collections
use std::thread; thread::spawn(|| { ... });

Spawn a new thread

Concurrency
handle.join().unwrap();

Wait for thread to finish

Concurrency
Arc::new(Mutex::new(data))

Thread-safe shared mutable state

Concurrency
use std::sync::mpsc; let (tx, rx) = mpsc::channel();

Create message passing channel

Concurrency
tx.send(value).unwrap(); let received = rx.recv().unwrap();

Send and receive through channel

Concurrency
async fn fetch() -> Result<()> { ... }

Async function

Concurrency
let result = fetch().await?;

Await async result

Concurrency
Showing 66 of 66 snippets

Free Online Rust Cheatsheet

A searchable Rust quick reference covering ownership, borrowing, lifetimes, structs, enums, traits, error handling, collections, and concurrency. Copy any snippet with one click.

About this cheatsheet

A comprehensive Rust cheatsheet covering the language's unique features and patterns.

  • 60+ practical Rust snippets
  • 7 categories from basics to concurrency
  • Ownership and borrowing explained
  • Error handling patterns (Result, Option)
  • One-click copy to clipboard
  • Trait system and generics covered

100% free. No signup required. No data collected or sent anywhere.

Explore All Tools