Rust Cheat Sheet
Last updated
Hello World & structure
A Rust program starts at fn main; statements end in semicolons.
| Operation | Syntax |
|---|---|
| Entry point | fn main() { ... } |
| Print a line | println!("Hello, World!"); |
| Print with values | println!("{} is {}", name, age); |
| Print debug form | println!("{:?}", value); |
| Line comment | // comment |
| Use an item from a module | use std::collections::HashMap; |
| Build & run | cargo run |
| Build a release binary | cargo build --release |
Variables & types (let / mut)
Bindings are immutable by default; add mut to allow reassignment.
| Operation | Syntax |
|---|---|
| Immutable binding | let x = 5; |
| Mutable binding | let mut count = 0; |
| Explicit type | let age: u32 = 30; |
| Constant | const MAX: u32 = 100; |
| Shadowing | let x = x + 1; |
| Integer types | i32, u32, i64, usize |
| Other scalars | f64, bool, char |
| Tuple | let pair: (i32, &str) = (1, "a"); |
| Type conversion | let f = x as f64; |
Control flow
if is an expression, and Rust has three loop forms.
| Operation | Syntax |
|---|---|
| If / else | if x > 0 { ... } else { ... } |
| If as an expression | let y = if x > 0 { 1 } else { -1 }; |
| Infinite loop | loop { ... } |
| Loop returning a value | let v = loop { break 5; }; |
| While loop | while x < 100 { ... } |
| For over a range | for i in 0..10 { ... } |
| For over a collection | for item in &items { ... } |
| Break / continue | break;, continue; |
Functions
The last expression (no semicolon) is the return value.
| Operation | Syntax |
|---|---|
| Basic function | fn add(a: i32, b: i32) -> i32 { a + b } |
| Explicit return | fn f() -> i32 { return 5; } |
| No return value | fn log(msg: &str) { ... } |
| Take a reference | fn len(s: &String) -> usize { s.len() } |
| Closure | let add = |a, b| a + b; |
| Closure with type | let sq = |x: i32| -> i32 { x * x }; |
| Function as argument | fn apply(f: impl Fn(i32) -> i32) { ... } |
Ownership & borrowing
Each value has one owner; references borrow it without taking ownership.
| Operation | Syntax |
|---|---|
| Move (ownership transfers) | let b = a; (a no longer valid) |
| Clone (deep copy) | let b = a.clone(); |
| Immutable borrow | let r = &x; |
| Mutable borrow | let r = &mut x; |
| Borrow in a function | fn read(s: &String) { ... } |
| Dereference | *r |
| Borrowing rule | Many & OR one &mut at a time, not both |
| Slice (borrows a range) | let part = &arr[1..3]; |
Structs & enums
Structs group related data; enums model a value that is one of several variants.
| Operation | Syntax |
|---|---|
| Define a struct | struct Point { x: i32, y: i32 } |
| Create an instance | let p = Point { x: 1, y: 2 }; |
| Access a field | p.x |
| Tuple struct | struct Pair(i32, i32); |
| Method (impl block) | impl Point { fn dist(&self) -> f64 { ... } } |
| Associated function | impl Point { fn new() -> Self { ... } } |
| Define an enum | enum Shape { Circle(f64), Rect(f64, f64) } |
| Enum with named fields | enum Msg { Move { x: i32, y: i32 } } |
| Derive traits | #[derive(Debug, Clone)] |
Pattern matching (match)
match compares a value against patterns and must be exhaustive.
| Operation | Syntax |
|---|---|
| Match on values | match x { 1 => "one", _ => "other" } |
| Match an enum | match shape { Shape::Circle(r) => ... } |
| Match a range | match n { 1..=5 => ..., _ => ... } |
| Bind with a guard | match x { n if n > 0 => ... } |
| Match a tuple | match point { (0, y) => ..., (x, _) => ... } |
| if let (single pattern) | if let Some(v) = opt { ... } |
| while let | while let Some(v) = stack.pop() { ... } |
| Destructure a struct | let Point { x, y } = p; |
Traits & generics
Traits define shared behavior; generics make code work over many types.
| Operation | Syntax |
|---|---|
| Define a trait | trait Area { fn area(&self) -> f64; } |
| Implement a trait | impl Area for Circle { fn area(&self) -> f64 { ... } } |
| Default method | trait Greet { fn hi(&self) { ... } } |
| Generic function | fn largest<T: PartialOrd>(list: &[T]) -> &T { ... } |
| Generic struct | struct Wrapper<T> { value: T } |
| Trait bound (where) | fn f<T>(x: T) where T: Display { ... } |
| impl Trait argument | fn print(item: impl Display) { ... } |
| Trait object | let shapes: Vec<Box<dyn Area>> = ...; |
Error handling (Result / Option)
Rust models absence with Option and recoverable errors with Result.
| Operation | Syntax |
|---|---|
| Optional value | Option<T>: Some(v) or None |
| Result type | Result<T, E>: Ok(v) or Err(e) |
| Return a Result | fn read() -> Result<String, Error> { ... } |
| Propagate with ? | let data = read()?; |
| Unwrap (panics on None/Err) | opt.unwrap() |
| Default value | opt.unwrap_or(0) |
| Map a value | opt.map(|v| v + 1) |
| Handle both arms | match res { Ok(v) => ..., Err(e) => ... } |
| Convert Option to Result | opt.ok_or("missing")? |
Common collections (Vec / HashMap)
Vec is a growable array; HashMap is a key-value store.
| Operation | Syntax |
|---|---|
| Create a vector | let mut v: Vec<i32> = Vec::new(); |
| Vector literal | let v = vec![1, 2, 3]; |
| Push / pop | v.push(4);, v.pop(); |
| Index access | v[0] |
| Safe access | v.get(0) returns Option<&T> |
| Iterate | for x in &v { ... } |
| Length | v.len() |
| Create a map | let mut m: HashMap<String, i32> = HashMap::new(); |
| Insert / get | m.insert(k, v);, m.get(&k) |
| Entry API | *m.entry(k).or_insert(0) += 1; |
The Rust syntax you reach for most, on one page. This Rust cheat sheet is a quick reference for the core language - variables and mutability, ownership and borrowing, structs and enums, pattern matching, traits and generics, and the Result and Option types behind Rust's error handling.
Everything here is standard Rust that compiles on a recent stable toolchain. Copy what you need, or try every snippet live in the Rust playground - no cargo install required.
Rust cheat sheet FAQ
Is this Rust cheat sheet free?
What are ownership and borrowing in Rust?
&x for an immutable borrow or &mut x for a mutable one. The compiler enforces one rule: you can have many immutable borrows or exactly one mutable borrow at a time, which prevents data races at compile time.What is the difference between Result and Option in Rust?
Option<T> represents a value that may be absent - it is either Some(v) or None, and you use it when there is no error to report, just a missing value. Result<T, E> represents an operation that can fail - it is either Ok(v) or Err(e), carrying an error value when something goes wrong. Use Option for "maybe there" and Result for "this could fail"; the ? operator propagates both.