Rust Cheat Sheet
Free Rust cheat sheet: the most-used Rust syntax and methods at a glance — searchable and beginner-friendly.
Basics
| Concept | Syntax | Example |
|---|---|---|
| Immutable / mutable binding Variables are immutable by default; add mut to change them. | let x = ... / let mut y = ... | let x = 5;
let mut count = 0; |
| Type annotation Types are inferred but can be written explicitly. | let x: Type = ... | let age: u32 = 36; |
| Function The last expression without ; is the return value. | fn name(p: T) -> R { ... } | fn add(a: i32, b: i32) -> i32 {
a + b
} |
| Main entry point Execution starts here. | fn main() { ... } | fn main() {
println!("Hello");
} |
| Print {} is a placeholder; macros end with !. | println!("{}", x) | println!("Count: {count}"); |
Ownership & Borrowing
| Concept | Syntax | Example |
|---|---|---|
| Move Ownership moves; the original binding is invalidated. | let b = a; | let s1 = String::from("hi");
let s2 = s1; // s1 no longer valid |
| Immutable borrow A shared reference; you can have many at once. | &x | fn len(s: &String) -> usize { s.len() } |
| Mutable borrow Exclusive reference; only one allowed at a time. | &mut x | fn push(s: &mut String) { s.push('!'); } |
| Clone Deep copy so both bindings stay valid. | x.clone() | let s2 = s1.clone(); |
| Slice A borrowed view into part of a collection or string. | &v[a..b] | let part = &arr[1..3]; |
Structs & Enums
| Concept | Syntax | Example |
|---|---|---|
| Struct A named record of typed fields. | struct S { field: T } | struct Point {
x: i32,
y: i32,
} |
| Methods (impl) &self borrows the instance the method is called on. | impl S { fn m(&self) {} } | impl Point {
fn sum(&self) -> i32 { self.x + self.y }
} |
| Enum A type that is one of several variants, each able to hold data. | enum E { A, B(T) } | enum Shape {
Circle(f64),
Rectangle(f64, f64),
} |
| Pattern match Must be exhaustive; use _ for a catch-all. | match x { ... } | match shape {
Shape::Circle(r) => 3.14 * r * r,
Shape::Rectangle(w, h) => w * h,
} |
| Option type Rust's null-free way to represent an absent value. | Option<T> (Some/None) | let maybe: Option<i32> = Some(5); |
Collections
| Concept | Syntax | Example |
|---|---|---|
| Vector A growable, heap-allocated array. | Vec<T> / vec![...] | let mut v = vec![1, 2, 3];
v.push(4); |
| Array Fixed-size, stack-allocated sequence. | [T; N] | let arr = [0; 5]; // five zeros |
| HashMap Key-value store; must be imported from std::collections. | HashMap<K, V> | use std::collections::HashMap;
let mut m = HashMap::new();
m.insert("a", 1); |
| Iterate Borrow with & so the collection stays usable afterward. | for x in &coll | for n in &v {
println!("{n}");
} |
| Iterator chains Lazy adapters; collect() runs them into a collection. | .iter().map().filter().collect() | let evens: Vec<i32> = v.iter().filter(|&&x| x % 2 == 0).cloned().collect(); |
Traits & Generics
| Concept | Syntax | Example |
|---|---|---|
| Generic function T is a type parameter constrained by trait bounds. | fn f<T>(x: T) | fn largest<T: PartialOrd>(a: T, b: T) -> T {
if a > b { a } else { b }
} |
| Define a trait A shared interface, like an abstract type. | trait Name { fn m(&self); } | trait Area {
fn area(&self) -> f64;
} |
| Implement a trait Provides the trait's behavior for a concrete type. | impl Trait for Type | impl Area for Circle {
fn area(&self) -> f64 { 3.14 * self.r * self.r }
} |
| Trait bound Restricts T to types implementing the trait. | <T: Trait> | fn print_all<T: std::fmt::Display>(items: &[T]) { } |
| Derive traits Auto-implements common traits like Debug and Clone. | #[derive(...)] | #[derive(Debug, Clone)]
struct Point { x: i32 } |
Error Handling
| Concept | Syntax | Example |
|---|---|---|
| Result type Represents success (Ok) or failure (Err). | Result<T, E> (Ok/Err) | fn parse(s: &str) -> Result<i32, std::num::ParseIntError> {
s.parse()
} |
| Question-mark operator Returns early with the error if the Result is Err. | expr? | let n = s.parse::<i32>()?; |
| Unwrap / expect Panics on Err/None. expect adds a custom message. | x.unwrap() / x.expect("msg") | let n = "5".parse::<i32>().unwrap(); |
| Match on Result Handle both outcomes explicitly. | match r { Ok(v) => .., Err(e) => .. } | match parse("5") {
Ok(n) => println!("{n}"),
Err(e) => println!("{e}"),
} |
| Panic Aborts the program; for truly unrecoverable bugs. | panic!("message") | panic!("unrecoverable error"); |