let x = 5; Immutable variable binding
let mut x = 5; Mutable variable binding
const MAX: u32 = 100; Compile-time constant
let x: i32 = 10; Explicit type annotation
i8 i16 i32 i64 i128 isize
u8 u16 u32 u64 u128 usize Integer types (signed/unsigned)
f32 f64 Floating point types
let s = String::from("hello"); Heap-allocated string
let s: &str = "hello"; String slice (borrowed reference)
let arr = [1, 2, 3]; Fixed-size array
let tup: (i32, f64, &str) = (1, 2.0, "hi"); Tuple with mixed types
if condition {
...
} else if other {
...
} else {
...
} If/else (expression, not statement)
for item in &vec { ... } For loop over iterator
loop { break; } Infinite loop with explicit break
while condition { ... } While loop
println!("x = {x}, y = {}", y); Print with formatting macros
let s2 = s1; Move ownership (s1 is invalid after)
let s2 = s1.clone(); Deep copy (both remain valid)
fn take(s: String) { ... } Function takes ownership of arg
fn borrow(s: &String) { ... } Immutable borrow (reference)
fn mutate(s: &mut String) { ... } Mutable borrow
let r = &x; Create immutable reference
let r = &mut x; Create mutable reference
'a Lifetime annotation (generic lifetime)
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str Function with lifetime parameters
struct User {
name: String,
age: u32,
} Struct definition
let u = User { name: String::from("A"), age: 30 }; Struct instantiation
impl User {
fn new(name: &str) -> Self { ... }
} Method implementation block
struct Point(f64, f64); Tuple struct
enum Color {
Red,
Green,
Blue,
Rgb(u8, u8, u8),
} Enum with variants (some with data)
enum Option<T> { Some(T), None } Option type (nullable value)
enum Result<T, E> { Ok(T), Err(E) } Result type (success or error)
match value {
Pattern => expr,
_ => default,
} Pattern matching (must be exhaustive)
if let Some(x) = optional { ... } Destructure single pattern
#[derive(Debug, Clone, PartialEq)] Auto-derive common traits
trait Summary {
fn summarize(&self) -> String;
} Trait definition
impl Summary for Article {
fn summarize(&self) -> String { ... }
} Implement trait for type
fn notify(item: &impl Summary) Trait bound (impl syntax)
fn notify<T: Summary + Display>(item: &T) Multiple trait bounds
fn returns() -> impl Summary Return type implementing trait
dyn Trait Dynamic dispatch (trait object)
Box<dyn Trait> Heap-allocated trait object
let f = File::open("f.txt")?; Propagate error with ? operator
unwrap() Panic on Err/None (use in tests only)
expect("msg") Panic with custom message on Err/None
unwrap_or(default) Return default on Err/None
unwrap_or_else(|| compute()) Return computed default on Err/None
match result {
Ok(val) => ...,
Err(e) => ...,
} Handle Result with match
map_err(|e| MyError::from(e)) Transform error type
panic!("critical error") Unrecoverable error (abort)
let v: Vec<i32> = Vec::new(); Create empty vector
let v = vec![1, 2, 3]; Create vector with values (macro)
v.push(4); Add element to vector
v.pop(); Remove and return last element
v.iter().map(|x| x * 2).collect::<Vec<_>>() Transform with iterator chain
v.iter().filter(|x| **x > 2).collect::<Vec<_>>() Filter with iterator
let mut map = HashMap::new();
map.insert("key", value); Create and populate HashMap
map.get("key") Get value from HashMap (returns Option)
map.entry("key").or_insert(0); Insert if key doesn't exist
let set: HashSet<i32> = HashSet::new(); Create HashSet (unique values)
use std::thread;
thread::spawn(|| { ... }); Spawn a new thread
handle.join().unwrap(); Wait for thread to finish
Arc::new(Mutex::new(data)) Thread-safe shared mutable state
use std::sync::mpsc;
let (tx, rx) = mpsc::channel(); Create message passing channel
tx.send(value).unwrap();
let received = rx.recv().unwrap(); Send and receive through channel
async fn fetch() -> Result<()> { ... } Async function
let result = fetch().await?; Await async result
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.