Rust Cheat Sheet
A quick lookup page for things you’ll want to check without re-reading a whole lesson. Each section links back to the page that explains it properly.
Keywords
Section titled “Keywords”| Keyword | Meaning |
|---|---|
let |
Declare a variable (Variables) |
mut |
Make a variable or reference mutable (Variables) |
const |
Declare a constant (Variables) |
fn |
Declare a function (Functions) |
struct |
Declare a struct (Structs) |
enum |
Declare an enum (Enums) |
impl |
Add methods to a type (Structs, Traits) |
trait |
Declare a trait (Traits) |
match |
Pattern match on a value (Match) |
if let / while let |
Match a single pattern (If Let / While Let) |
loop / while / for |
The three loop types (Loops, While, For) |
break / continue |
Control a loop (Break/Continue) |
mod |
Declare a module (Modules) |
pub |
Make an item public outside its module (Modules) |
use |
Bring a path into scope (Modules) |
unsafe |
Unlock raw pointers and other checked-by-you operations (Unsafe) |
move |
Force a closure to take ownership of captured values (Concurrency) |
& / &mut |
Borrow / mutably borrow a value (Borrowing) |
Common String methods
Section titled “Common String methods”| Method | What it does |
|---|---|
.len() |
Length in bytes |
.trim() |
Removes leading/trailing whitespace |
.to_uppercase() / .to_lowercase() |
Case conversion |
.contains(pat) |
Whether a substring/pattern is present |
.replace(from, to) |
Replace all matches |
.push_str(s) |
Append a &str |
.push(c) |
Append a single char |
.chars() |
Iterate character by character |
.split(pat) |
Split into an iterator of substrings |
.parse::<T>() |
Convert text into another type (returns Result) |
See the Strings page for details and examples.
Common Vec methods
Section titled “Common Vec methods”| Method | What it does |
|---|---|
.push(x) |
Add to the end |
.pop() |
Remove and return the last item (Option) |
.remove(i) |
Remove the item at index i |
.len() |
Number of items |
.is_empty() |
Whether the vector has no items |
.get(i) |
Safe indexed access (Option, doesn’t panic) |
.iter() |
Iterate by reference |
.contains(&x) |
Whether a value is present |
.sort() |
Sort in place |
.sort_by_key(|x| ...) |
Sort by a field or computed key |
.dedup() |
Remove consecutive duplicates (sort first) |
See the Vectors, Sorting & Searching, and Iterators pages for details and examples.
Which collection should I use?
Section titled “Which collection should I use?”| Type | Use it when you need… |
|---|---|
Vec<T> |
An ordered, growable list |
HashMap<K, V> |
Fast lookup of a value by key |
HashSet<T> |
Unique items and fast “is it in here?” checks |
BTreeMap<K, V> |
Key-value pairs kept in sorted key order |
VecDeque<T> |
A queue — push and pop at both ends |
See the HashMaps and HashSet & BTreeMap pages for details and examples.
Option and Result
Section titled “Option and Result”| Method | Works on | What it does |
|---|---|---|
.unwrap() |
Both | Get the value, panics if None/Err |
.expect("msg") |
Both | Like .unwrap(), with a custom panic message |
.unwrap_or(default) |
Both | Get the value, or a fallback |
.is_some() / .is_none() |
Option |
Check which variant it is |
.is_ok() / .is_err() |
Result |
Check which variant it is |
? |
Both | Return early on None/Err |
See the Option and Result pages for details and examples.
Formatting specifiers (println!, format!)
Section titled “Formatting specifiers (println!, format!)”| Specifier | What it prints |
|---|---|
{} |
Normal display (needs the Display trait) |
{:?} |
Debug format |
{:#?} |
Pretty-printed debug format |
{:.2} |
2 decimal places |
{:5} |
Pad to a width of 5 |
{name} |
Inline a variable named name |
See the Output page for details and examples.
Cargo commands
Section titled “Cargo commands”| Command | What it does |
|---|---|
cargo new name |
Create a new project |
cargo run |
Build and run |
cargo check |
Check for errors fast, without building |
cargo test |
Run your tests |
cargo add crate |
Add a dependency |
cargo fmt |
Format your code |
cargo clippy |
Lint your code for common mistakes |
cargo build --release |
Build an optimized binary |
See the Cargo & Crates page for details and examples.
Range syntax
Section titled “Range syntax”| Syntax | Meaning |
|---|---|
1..5 |
1 up to, not including, 5 |
1..=5 |
1 up to and including 5 |
..3 |
From the start up to, not including, 3 |
2.. |
From 2 to the end |
.. |
Everything |
See the For and Slices pages for details and examples.
Popular crates
Section titled “Popular crates”| You need… | Crate | Lesson |
|---|---|---|
| JSON (and other formats) | serde + serde_json |
JSON with Serde |
| Async code, timers, networking | tokio |
Async/Await |
| A command-line interface | clap |
CLI Tool with clap |
| Easy error handling | anyhow, thiserror |
anyhow & thiserror |
| Random numbers | rand |
Random Numbers |
| Regular expressions | regex |
Regular Expressions |
| Dates and times | chrono |
Dates & Times |
| Logging | log + env_logger, tracing |
Logging |
| A web server | axum |
Web API with Axum |
Add any of them with cargo add <crate>. See Cargo & Crates for how to choose a good crate.
Read more
Section titled “Read more”- Rust Language Cheat Sheet — cheats.rs: a much bigger one-page reference, from syntax to memory layout, once you want more detail.
- Appendix B: Operators and Symbols — The Rust Book: every operator and symbol in Rust, with what it means.
- std::fmt — standard library docs: the full formatting syntax behind
println!andformat!: width, padding, precision and more. - Cargo Commands — The Cargo Book: every
cargocommand and its options. - The Rust Standard Library: the complete API docs for
String,Vec,Option,Resultand the rest. Use the search box at the top.