Menu

Rust Cheat Sheet

Last updated

Hello World & structure

A Rust program starts at fn main; statements end in semicolons.

OperationSyntax
Entry pointfn main() { ... }
Print a lineprintln!("Hello, World!");
Print with valuesprintln!("{} is {}", name, age);
Print debug formprintln!("{:?}", value);
Line comment// comment
Use an item from a moduleuse std::collections::HashMap;
Build & runcargo run
Build a release binarycargo build --release

Variables & types (let / mut)

Bindings are immutable by default; add mut to allow reassignment.

OperationSyntax
Immutable bindinglet x = 5;
Mutable bindinglet mut count = 0;
Explicit typelet age: u32 = 30;
Constantconst MAX: u32 = 100;
Shadowinglet x = x + 1;
Integer typesi32, u32, i64, usize
Other scalarsf64, bool, char
Tuplelet pair: (i32, &str) = (1, "a");
Type conversionlet f = x as f64;

Control flow

if is an expression, and Rust has three loop forms.

OperationSyntax
If / elseif x > 0 { ... } else { ... }
If as an expressionlet y = if x > 0 { 1 } else { -1 };
Infinite looploop { ... }
Loop returning a valuelet v = loop { break 5; };
While loopwhile x < 100 { ... }
For over a rangefor i in 0..10 { ... }
For over a collectionfor item in &items { ... }
Break / continuebreak;, continue;

Functions

The last expression (no semicolon) is the return value.

OperationSyntax
Basic functionfn add(a: i32, b: i32) -> i32 { a + b }
Explicit returnfn f() -> i32 { return 5; }
No return valuefn log(msg: &str) { ... }
Take a referencefn len(s: &String) -> usize { s.len() }
Closurelet add = |a, b| a + b;
Closure with typelet sq = |x: i32| -> i32 { x * x };
Function as argumentfn apply(f: impl Fn(i32) -> i32) { ... }

Ownership & borrowing

Each value has one owner; references borrow it without taking ownership.

OperationSyntax
Move (ownership transfers)let b = a; (a no longer valid)
Clone (deep copy)let b = a.clone();
Immutable borrowlet r = &x;
Mutable borrowlet r = &mut x;
Borrow in a functionfn read(s: &String) { ... }
Dereference*r
Borrowing ruleMany & 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.

OperationSyntax
Define a structstruct Point { x: i32, y: i32 }
Create an instancelet p = Point { x: 1, y: 2 };
Access a fieldp.x
Tuple structstruct Pair(i32, i32);
Method (impl block)impl Point { fn dist(&self) -> f64 { ... } }
Associated functionimpl Point { fn new() -> Self { ... } }
Define an enumenum Shape { Circle(f64), Rect(f64, f64) }
Enum with named fieldsenum Msg { Move { x: i32, y: i32 } }
Derive traits#[derive(Debug, Clone)]

Pattern matching (match)

match compares a value against patterns and must be exhaustive.

OperationSyntax
Match on valuesmatch x { 1 => "one", _ => "other" }
Match an enummatch shape { Shape::Circle(r) => ... }
Match a rangematch n { 1..=5 => ..., _ => ... }
Bind with a guardmatch x { n if n > 0 => ... }
Match a tuplematch point { (0, y) => ..., (x, _) => ... }
if let (single pattern)if let Some(v) = opt { ... }
while letwhile let Some(v) = stack.pop() { ... }
Destructure a structlet Point { x, y } = p;

Traits & generics

Traits define shared behavior; generics make code work over many types.

OperationSyntax
Define a traittrait Area { fn area(&self) -> f64; }
Implement a traitimpl Area for Circle { fn area(&self) -> f64 { ... } }
Default methodtrait Greet { fn hi(&self) { ... } }
Generic functionfn largest<T: PartialOrd>(list: &[T]) -> &T { ... }
Generic structstruct Wrapper<T> { value: T }
Trait bound (where)fn f<T>(x: T) where T: Display { ... }
impl Trait argumentfn print(item: impl Display) { ... }
Trait objectlet shapes: Vec<Box<dyn Area>> = ...;

Error handling (Result / Option)

Rust models absence with Option and recoverable errors with Result.

OperationSyntax
Optional valueOption<T>: Some(v) or None
Result typeResult<T, E>: Ok(v) or Err(e)
Return a Resultfn read() -> Result<String, Error> { ... }
Propagate with ?let data = read()?;
Unwrap (panics on None/Err)opt.unwrap()
Default valueopt.unwrap_or(0)
Map a valueopt.map(|v| v + 1)
Handle both armsmatch res { Ok(v) => ..., Err(e) => ... }
Convert Option to Resultopt.ok_or("missing")?

Common collections (Vec / HashMap)

Vec is a growable array; HashMap is a key-value store.

OperationSyntax
Create a vectorlet mut v: Vec<i32> = Vec::new();
Vector literallet v = vec![1, 2, 3];
Push / popv.push(4);, v.pop();
Index accessv[0]
Safe accessv.get(0) returns Option<&T>
Iteratefor x in &v { ... }
Lengthv.len()
Create a maplet mut m: HashMap<String, i32> = HashMap::new();
Insert / getm.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?
Yes. This Rust cheat sheet is completely free, with no sign-up required. Bookmark it and come back whenever you need to look up a match pattern, trait bound, or collection method.
What are ownership and borrowing in Rust?
Ownership is Rust's memory model: every value has exactly one owner, and the value is freed when that owner goes out of scope. Borrowing lets you access a value without taking ownership by using a reference - &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.
Can I practice Rust online?
Yes. Open the Rust playground to compile and run any snippet from this cheat sheet in your browser - no cargo or toolchain to install. When you want structure, Coddy's free interactive Rust course takes you from variables and ownership to traits and error handling step by step.
Is this cheat sheet good for beginners?
Yes. It is organized from the most common topics (variables, control flow, functions) down to advanced ones (traits, generics, error handling), so you can use the top sections on day one and grow into ownership and the rest.
Coddy programming languages illustration

Learn Rust with Coddy

GET STARTED