Rust Cheat Sheet
Quick reference from FreeCodingCourses.com
Variables and types
let x = 5;- immutable by default.
let mut count = 0;- mut makes it changeable.
let x: i32 = 5;- explicit type. Also u32, f64, bool, char.
const MAX: u32 = 100;- a compile-time constant.
let name = String::from("Ada");- an owned, growable string.
Ownership and borrowing
let b = a;- for owned types this moves a; a is no longer usable.
let b = &a;- borrow a reference instead of moving.
fn read(s: &String)- borrow: the caller keeps ownership.
fn edit(s: &mut String)- a mutable borrow lets you change it.
let c = a.clone();- make a deep copy when you really need two owners.
Structs and enums
struct User { name: String, age: u32 }- a struct groups fields.
let u = User { name: n, age: 36 };- create one.
enum Shape { Circle(f64), Rect(f64, f64) }- an enum: one of several variants, with data.
impl User { fn greet(&self) -> String { ... } }- methods go in an impl block.
Pattern matching
match n { 0 => "zero", _ => "other", }- match must cover every case. _ is the catch-all.
match shape { Shape::Circle(r) => ..., }- destructure enum data as you match.
if let Some(v) = maybe { ... }- match one case without a full match.
Collections and iterators
let mut xs = vec![1, 2, 3];- a Vec, Rust's growable array.
xs.push(4); xs.len();- add and count.
for x in &xs { ... }- iterate by reference (keeps xs usable).
let ys: Vec<i32> = xs.iter().map(|n| n * 2).collect();- transform into a new collection (annotate the target type).
Result and Option (no null, no exceptions)
Option<T>: Some(v) or None- a value that might be absent.
Result<T, E>: Ok(v) or Err(e)- an operation that might fail.
let v = maybe.unwrap_or(0);- get the value or a default.
let v = parse()?;- the ? operator returns early on Err.
Unlock the full Rust cheat sheet
You're seeing 2 of 6 sections. Drop your email to open the rest plus the gotchas, and save the whole thing as a printable PDF.
No spam, unsubscribe anytime. See our privacy policy.