glunty

Rust Language Cheat Sheet

A searchable reference of core Rust syntax and what each piece does.

Common Rust snippets with a plain-English description of what each one does
Snippet What it does
fn main() {} The entry point that runs first when a Rust program starts.
let x = 5; Bind a value to an immutable variable named x.
let mut x = 5; Bind a mutable variable whose value you can change later.
const MAX: u32 = 100; Declare a compile-time constant, which always needs a type annotation.
let x: i32 = 5; Annotate a binding with an explicit type, here a 32-bit signed integer.
u32, f64, bool, char Core scalar types: unsigned integer, float, boolean, and a single Unicode character.
let c = 'z'; A char literal uses single quotes and holds one Unicode scalar value.
String vs &str String is a growable owned heap string; &str is a borrowed string slice.
println!("{}", x) Print a line to stdout, filling each placeholder with an argument.
let x = x + 1; Shadowing re-declares a name with let, hiding the earlier variable.
let b = a; For a non-Copy type this moves ownership from a to b, leaving a unusable.
let r = &x; Borrow an immutable reference to x without taking ownership.
let r = &mut x; Borrow a mutable reference so you can change x through r.
let b = a.clone(); Make a deep copy so a and b each own separate data.
i32, bool, char are Copy Copy types are duplicated on assignment instead of being moved.
fn f<'a>(x: &'a str) -> &'a str A lifetime parameter named a ties the output reference to the input.
let s: &'static str = "hi"; The static lifetime lasts for the entire run of the program.
let part = &v[1..3]; A slice borrows a contiguous range of a Vec or array without copying.
let v: Vec<i32> = Vec::new(); Create an empty growable vector of i32 values.
let v = vec![1, 2, 3]; Create a vector pre-filled with the given elements.
v.push(4); Append an element to the end of a vector.
let mut m: HashMap<&str, i32> = HashMap::new(); Create an empty hash map of key-value pairs.
m.insert("a", 1); Insert a value under a key, replacing any earlier value.
m.get("a") Look up a key and get back an Option holding the value.
let a = [1, 2, 3]; A fixed-size array whose length is known at compile time.
let t = (1, "hi", 3.0); Group several values of different types into one tuple.
for x in &v {} Loop over each element of a vector by reference.
if x > 5 {} Run a block only when the condition is true.
if let Some(x) = opt {} Run a block only when a value matches the given pattern.
match x { 1 => "one", _ => "other" } Compare a value against patterns and run the first arm that fits.
loop {} Repeat a block forever until you break out of it.
let v = loop { break 5; }; A loop is an expression that can return a value through break.
while x < 5 {} Repeat a block while the condition stays true.
while let Some(x) = it.next() {} Keep looping for as long as the pattern keeps matching.
for i in 0..5 {} Loop over a range from 0 up to but not including 5.
fn add(a: i32, b: i32) -> i32 { a + b } Define a function that returns i32; the final expression is the result.
let f = |x| x + 1; Define an anonymous closure that can capture its surrounding scope.
impl Point { fn dist(&self) -> f64 {} } Define methods on a type inside an impl block.
Point::new(1, 2) Call an associated function, often used as a constructor.
fn first<T>(list: &[T]) -> &T A generic function that works over any type T.
trait Area { fn area(&self) -> f64; } Declare a trait, a shared set of methods a type can implement.
impl Area for Circle {} Implement a trait for a specific type.
fn show<T: Display>(x: T) A trait bound requires the generic type to implement a trait.
struct Point { x: i32, y: i32 } Define a struct that groups named fields into one type.
let p = Point { x: 1, y: 2 }; Create a struct instance by giving each field a value.
enum Dir { Up, Down, Left } Define an enum, a type that is exactly one of several variants.
enum Shape { Circle(f64), Rect(f64, f64) } Enum variants can each carry their own data.
let x: Option<i32> = Some(5); Some wraps a present value inside an Option.
let n: Option<i32> = None; None marks the absence of a value in an Option.
let r: Result<i32, String> = Ok(5); Ok holds a success value; Err would hold an error instead.
#[derive(Debug, Clone)] Auto-implement common traits such as Debug and Clone for a type.
impl Dir { fn name(&self) -> &str {} } Attach methods to a struct or enum in an impl block.
fn read() -> Result<String, Error> A function that can fail returns a Result.
x.unwrap() Get the value out of Some or Ok, or panic if it is None or Err.
x.expect("failed") Like unwrap but panics with a message you choose.
let n = parse()?; The question mark returns the error early or unwraps the Ok value.
panic!("boom"); Abort the current thread right away with an error message.
match r { Ok(v) => v, Err(e) => 0 } Handle the success and failure branches of a Result explicitly.
x.unwrap_or(0) Return the contained value or a fallback when it is None or Err.
fn f() -> Result<(), Box<dyn Error>> A boxed error type lets the question mark propagate many error kinds.

Runs entirely in your browser. Nothing you type is sent anywhere; open DevTools and watch the Network tab to verify zero requests.

What this tool does

This is a searchable quick reference for everyday Rust syntax, from variable bindings and ownership to collections, control flow, traits, enums, and error handling. Each row pairs a small snippet with a plain-English note on what it does. Type in the filter box to search across both columns, or tap a category button to focus on one area. The whole list is built into the page, so it works offline and sends nothing anywhere.

How to use it

Start typing in the Filter box. Entering match jumps to the match expression; entering borrow or ownership surfaces the reference rules; entering Result or unwrap shows the error-handling snippets. The category buttons (Basics, Ownership, Collections, Control flow, Functions and traits, Enums and structs, Errors) narrow the table to one area and combine with the text filter, so you can pick Errors and type unwrap to see just those. Clear the box to see the full sheet again.

Common use cases

  • Recalling exact syntax you reach for rarely, such as a while let loop or a trait bound.
  • Copying a correct snippet into your editor instead of guessing.
  • Teaching a teammate the difference between Option and Result.
  • Looking up how the ? operator propagates errors.
  • Reviewing core Rust before an interview or a new project.

Common pitfalls

  • Using a value after it moved. Once you assign or pass a non-Copy value, the original binding is invalid; borrow it with & or call clone if you still need it.
  • Mixing shared and mutable borrows. You may hold many &T references or one &mut T, but not both at once; the borrow checker rejects the overlap.
  • Calling unwrap in real code. Both unwrap and expect panic on None or Err; prefer match, the ? operator, or unwrap_or to handle failure gracefully.
  • Confusing String and &str. Functions that only read text should take &str so they accept both string literals and owned strings.

Frequently asked questions

What is ownership in Rust?
Ownership is the set of rules that governs how Rust manages memory. Each value has a single owner, and when that owner goes out of scope the value is dropped and its memory freed. Assigning or passing a non-Copy value moves ownership rather than copying it, which lets Rust free memory safely without a garbage collector.
What does the borrow checker do?
The borrow checker is the part of the compiler that enforces the borrowing rules at compile time. You may have many shared references (one or more &T) or exactly one mutable reference (&mut T) to a value, but never both at once, and no reference may outlive the value it points to. These checks catch data races and dangling pointers before your program ever runs.
What is the difference between String and str?
String is an owned, growable, heap-allocated string that you can modify. str, almost always seen as the borrowed slice &str, is a fixed view into string data that someone else owns, such as a string literal baked into the binary. In short, use String when you need ownership or need to grow the text, and &str when you only need to read it.
What are Option and Result?
Option and Result are enums that make missing values and errors explicit. Option is either Some(value) or None, and it replaces null for values that may be absent. Result is either Ok(value) or Err(error), and it models operations that can fail. Because they are ordinary enums, the compiler forces you to handle both cases before you can use the inner value.
What does the question mark operator do?
The question mark operator is shorthand for propagating errors. When placed after an expression that returns a Result or Option, it unwraps the Ok or Some value and lets execution continue; if the value is Err or None, it returns that from the enclosing function immediately. It only works inside a function whose return type is a compatible Result or Option.
What is the difference between move, borrow, and clone?
Moving transfers ownership of a value to a new binding, after which the old binding can no longer be used. Borrowing with an ampersand lends temporary access without taking ownership, so the original owner keeps the value. Cloning with clone makes a full independent copy, which costs more but leaves both values usable. Simple Copy types like integers are duplicated automatically instead of moved.
Does this cheat sheet send my searches anywhere?
No. The entire snippet list is baked into the page and every search and filter runs locally in your browser with JavaScript, so nothing you type leaves your device. Open your browser DevTools and watch the Network tab while you search to confirm there are zero requests.

Embed this tool

Free for any use; attribution appreciated. Paste this on your site:

The embed runs the same tool that lives at this URL. No tracking; no ads inside the embed. Resize height as needed for your layout.

Cite this tool

For academic, journalistic, or technical references. Pick a format:

Citations use 2026 as the publication year. Access date is left as a fillable placeholder where the citation style expects one.

Embedded tool from glunty.com