Rust Cheatsheet
A complete Rust programming language cheatsheet from beginner to advanced — ownership, borrowing, lifetimes, traits, generics, error handling, concurrency, async, smart pointers, macros, modules, testing, and best practices.
Rust is a systems programming language that emphasizes memory safety, zero-cost abstractions, and fearless concurrency. The compiler enforces ownership and borrowing rules at compile time, eliminating entire classes of bugs without a garbage collector.
This cheatsheet goes from beginner fundamentals to intermediate and advanced topics.
# Installcurl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# Versionrustc --versioncargo --version
# New binary projectcargo new my_projectcd my_projectcargo run
# Library projectcargo new --lib my_lib
# Release buildcargo build --release
# Testcargo test
# Format & lintcargo fmtcargo clippyCargo.toml example:
[package]name = "my_project"version = "0.1.0"edition = "2024"
[dependencies]tokio = { version = "1", features = ["full"] }serde = { version = "1", features = ["derive"] }fn main() { println!("Hello, Rust!");}let x = 5; // immutable (default)let mut y = 10; // mutabley = 15;
const MAX_POINTS: u32 = 100_000; // compile-time constantstatic VERSION: &str = "1.0.0"; // 'static lifetime| Type | Description | Example |
|---|---|---|
i8 … i128, u8 … u128 |
Signed / unsigned integers | let x: i32 = -42; |
isize, usize |
Pointer-sized | indexing uses usize |
f32, f64 |
Floating point | let pi = 3.1416; |
bool |
true / false | let ok = true; |
char |
4-byte Unicode scalar | let c = 'R'; |
&str |
String slice | let s = "Rust"; |
String |
Owned, growable string | let s = String::from("Rust"); |
() |
Unit type | functions that return nothing |
Type inference & annotations:
let x = 42; // inferred as i32let y: u64 = 42;let z = 42u64; // suffixlet v: Vec<i32> = Vec::new();let s = String::from("hello");let slice: &str = &s[0..5]; // byte indices (careful with Unicode)let first = &s[..]; // whole string as slice
// Character-safe iterationfor c in s.chars() { println!("{}", c);}- Every value has a single owner.
- There can only be one owner at a time.
- When the owner goes out of scope, the value is dropped.
let s1 = String::from("hello");let s2 = s1; // move — s1 is no longer valid// println!("{}", s1); // error
let s3 = s2.clone(); // deep copyfn calculate_length(s: &String) -> usize { // immutable borrow s.len()}
fn change(s: &mut String) { // mutable borrow s.push_str(", world!");}
let mut s = String::from("hello");let len = calculate_length(&s);change(&mut s);Borrowing rules:
- Either one or more
&Tor exactly one&mut Tat a time. - You cannot move out of a value while it is borrowed.
// Returns the shorter of the two lifetimesfn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { y }}
struct ImportantExcerpt<'a> { part: &'a str,}
impl<'a> ImportantExcerpt<'a> { fn level(&self) -> i32 { 3 }}'static means the data lives for the entire duration of the program (string literals).
fn add(a: i32, b: i32) -> i32 { a + b // expression (no semicolon)}
fn main() { let sum = add(5, 3);}let add_one = |x| x + 1;let add_one = |x: i32| -> i32 { x + 1 };
let mut list = vec![1, 2, 3];list.iter_mut().for_each(|x| *x += 1);Closures implement one of: Fn, FnMut, FnOnce.
let v = vec![1, 2, 3];
let sum: i32 = v.iter() .map(|x| x * 2) .filter(|x| *x > 2) .sum();
// into_iter() → takes ownership// iter() → &T// iter_mut() → &mut TCommon adapters: map, filter, filter_map, flat_map, take, skip, zip, enumerate, fold, collect.
let number = 7;
if number < 5 { println!("small");} else if number > 5 { println!("large");} else { println!("equal");}
// if is an expressionlet status = if number % 2 == 0 { "even" } else { "odd" };
// loopsfor i in 1..=5 { println!("{}", i);}
// match (exhaustive)match number { 1 => println!("one"), 2 | 3 => println!("two or three"), 4..=9 => println!("four to nine"), _ => println!("something else"),}
// if let & let elseif let Some(x) = some_option { println!("{}", x);}
let Some(x) = some_option else { return;};let tup: (i32, f64, u8) = (500, 6.4, 1);let (x, y, z) = tup;
let a = [1, 2, 3, 4, 5];let first = a[0];
let mut v: Vec<i32> = Vec::new();v.push(5);let v = vec![1, 2, 3];use std::collections::{HashMap, HashSet, BTreeMap, VecDeque};
let mut scores = HashMap::new();scores.insert(String::from("Blue"), 10);scores.entry(String::from("Yellow")).or_insert(50);#[derive(Debug, Clone)]struct User { active: bool, username: String, email: String, sign_in_count: u64,}
impl User { fn new(email: String, username: String) -> Self { Self { active: true, username, email, sign_in_count: 1, } }
fn greet(&self) -> String { format!("Hello, {}!", self.username) }}enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(i32, i32, i32),}
// Option and Result are just enumsenum Option<T> { None, Some(T),}
enum Result<T, E> { Ok(T), Err(E),}use std::fs::File;use std::io::{self, Read};
fn read_username_from_file() -> Result<String, io::Error> { let mut username = String::new(); File::open("hello.txt")?.read_to_string(&mut username)?; Ok(username)}
// unwrap / expect — prototyping onlylet f = File::open("hello.txt").unwrap();let f = File::open("hello.txt").expect("Failed to open file");In production prefer ? together with crates such as thiserror or anyhow.
trait Summary { fn summarize(&self) -> String;
fn summarize_author(&self) -> String { String::from("(unknown)") }}
impl Summary for NewsArticle { fn summarize(&self) -> String { format!("{}, by {}", self.headline, self.author) }}
// Trait boundsfn notify<T: Summary>(item: &T) { println!("Breaking news! {}", item.summarize());}
fn notify2(item: &impl Summary) { /* same */ }
// Multiple boundsfn some_function<T, U>(t: &T, u: &U) -> i32where T: Display + Clone, U: Clone + Debug,{ // ...}Dynamic dispatch: Box<dyn Summary>.
| Type | Use case |
|---|---|
Box<T> |
Heap allocation, recursive types |
Rc<T> |
Single-threaded reference counting |
Arc<T> |
Multi-threaded reference counting |
RefCell<T> |
Runtime borrow checking (interior mutability) |
Mutex<T> / RwLock<T> |
Thread-safe mutability |
use std::rc::Rc;use std::cell::RefCell;
let value = Rc::new(RefCell::new(5));*value.borrow_mut() += 1;use std::thread;use std::sync::{mpsc, Arc, Mutex};
let handle = thread::spawn(|| { println!("hello from a thread");});handle.join().unwrap();#[tokio::main]async fn main() { let result = async_function().await;}
async fn async_function() -> String { // yields at .await points String::from("done")}Async in traits (stable since 1.75):
trait AsyncRead { async fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize>;}pub mod front_of_house { pub mod hosting { pub fn add_to_waitlist() {} }}
pub use crate::front_of_house::hosting;
// src/main.rsuse my_crate::hosting;Visibility is controlled with pub, pub(crate), pub(super).
macro_rules! vec_of_strings { ($($x:expr),*) => { { let mut temp_vec = Vec::new(); $(temp_vec.push($x.to_string());)* temp_vec } };}
let v = vec_of_strings!["one", "two", "three"];Procedural macros (#[derive], attribute, function-like) live in their own crate.
#[cfg(test)]mod tests { use super::*;
#[test] fn it_works() { assert_eq!(2 + 2, 4); }
#[test] #[should_panic(expected = "something went wrong")] fn should_panic() { panic!("something went wrong"); }
#[tokio::test] async fn async_test() { assert!(true); }}cargo testcargo test -- --nocapturecargo test test_name- Unsafe Rust:
unsafe { }blocks for raw pointers,unsafe fn,unsafe trait. Use only when truly necessary. - FFI: call C libraries with
extern "C". - Attributes:
#[derive(Debug, Clone, PartialEq)],#[inline],#[must_use],#[tokio::main]. - Constant evaluation:
const fn. - Never type:
!(diverging functions).
| Crate | Purpose |
|---|---|
serde |
Serialization |
tokio / async-std |
Async runtime |
thiserror / anyhow |
Error handling |
clap |
CLI argument parsing |
reqwest |
HTTP client |
tracing |
Logging & tracing |
rayon |
Data parallelism |
cargo add serde --features derivecargo add tokio --features full- Avoid
unwrap()/expect()in production. - Run
cargo clippyandcargo fmtregularly. - Prefer
&strwhen you do not need ownership. - Minimize cloning; prefer borrowing.
- Use edition 2024 (
edition = "2024"). - Document with
///and generate docs withcargo doc --open. - Resources: The Rust Book, Rust by Example, Rust Reference.
use std::collections::HashMap;
#[derive(Debug)]struct Student { name: String, grade: u32,}
impl Student { fn new(name: &str, grade: u32) -> Self { Student { name: String::from(name), grade, } }}
fn main() { let mut students: HashMap<String, Student> = HashMap::new();
students.insert( String::from("Rahim"), Student::new("Rahim", 85), ); students.insert( String::from("Karim"), Student::new("Karim", 90), );
for (key, student) in &students { println!("{}: grade = {}", key, student.grade); }
let rahim = students.get("Rahim").unwrap(); println!("Rahim's info: {:?}", rahim);}This cheatsheet targets modern Rust (2024 edition / recent stable). Always verify behavior against the version you are using.
Frequently asked questions
What is ownership in Rust and why does it matter?
Every value has a single owner. When the owner goes out of scope the value is dropped. This prevents memory leaks, double-frees, and data races at compile time without a garbage collector.
What is the difference between String and and str?
String is an owned, heap-allocated, growable string. and str is a string slice (a view into a string) that is usually cheap and often points to static or borrowed data.
When do I need lifetime annotations?
When the compiler cannot automatically figure out the relationship between references. You annotate with 'a so the compiler knows how long each reference is valid.
How do I handle errors in Rust?
Prefer Result<T, E> and the ? operator for recoverable errors. Use Option<T> when a value may be absent. Avoid unwrap/expect in production code.
How does async work in Rust?
async fn returns a Future. You .await it to drive the future to completion. A runtime such as Tokio or async-std is required to execute async code.