Rust Cheatsheet — Quick Reference
A concise Rust 2021 cheatsheet covering syntax, ownership, error handling and the most common std APIs — about 80% of everyday scenarios.
Rust Rust 2021 edition
rustc / cargo · Compiled · systems · functional · concurrent · Static · strongly typed · affine (move semantics)
Recommended Learning Path
First learn cargo new / run and println! → master variable bindings, ownership and borrowing (the Rust core) → dive into match, functions and closures → organise data with Vec / HashMap / iterators → understand traits and generics → handle errors with Result and ? → write concurrency with threads and channel → then learn networking, time and build/test as needed. The FAQ section is great for coming back to avoid pitfalls.
1.Hello World & Build Environment
Run Rust programs, cargo projects, and the toolchain.
Minimal program
fn main is the entry point. The println! macro prints output. Statements end with a semicolon.
Run & build
cargo run compiles and runs, cargo build produces binaries, cargo check is a fast type-check.
cargo project
cargo new initializes a project. Cargo.toml declares the package and dependencies. src/ holds source.
edition
edition declares the language edition. 2021 is current. rust-version declares the minimum toolchain.
Output macros
println! / print! for stdout, eprintln! for stderr, format! to build a String.
Command-line arguments
std::env::args returns CLI arguments. The first one is the program path.
Multiple files
mod declares a module. Submodule file or directory. use imports it.
Direct compilation
rustc compiles a single file. No cargo dependency. Good for exercises and small scripts.
2.Variables & Bindings
let bindings, mutability, shadowing, scope and types.
let & mut
let bindings are immutable by default. mut makes a binding mutable. Rust variables are immutable by default.
Shadowing
A same-named let shadows the previous binding. Can change type. Different from mut.
const & static
const is a compile-time constant. static is a static variable. Use SCREAMING_SNAKE names.
Type inference
The compiler infers types from context. Annotate explicitly when needed. Integers default to i32.
Destructuring bindings
let supports pattern destructuring. Tuples, structs, and arrays can be unpacked at once.
Scope
Block scope with {}. Variable lifetimes. Inner scope can read outer bindings.
Naming conventions
Rust naming conventions. snake_case for variables/functions, CamelCase for types.
Type conversions
as performs explicit numeric conversions. From/Into trait provide safe conversions.
3.Type System
Primitive types, tuples, structs, and enums.
Primitive types
Integers, floating-point, bool, char. Scalar types and their widths.
Integer types
i8-u128, usize/isize. Signed and unsigned. Platform-dependent sizes.
Floating-point numbers
f32 / f64 conform to IEEE 754. NaN, infinity, and arithmetic.
char type
char is a Unicode scalar value, 4 bytes. Use single-quote literals.
Tuples
Fixed-length heterogeneous collection. Indexed access. Destructuring. The empty tuple is ().
Structs
struct defines named fields. Construction, field access, and update syntax.
Enums
enum defines multiple variants. Variants may carry data. match exhaustively handles them.
Unit type
() means no value. Functions return () by default. The convention for no-return no-arg.
4.Ownership & References
Ownership, borrowing, references, and slices — the core of Rust memory safety.
Ownership
Each value has a single owner. Dropped automatically at end of scope. Moves rather than copies.
References
&T is a shared reference that doesn't transfer ownership. The original is still usable.
Mutable references
&mut T is a mutable reference. Only one mutable reference can exist at a time per scope.
Dereference
* accesses the value behind a reference. Dereference pairs with reference.
Lifetimes
'a annotates a reference's valid range. The borrow checker enforces validity. Elision rules.
Slices
&[T] is a view over contiguous elements. String slice is &str. Neither owns data.
Deref coercion
The Deref trait makes &String coerce to &str, etc. Convenient argument polymorphism.
Copy types
Types with Copy are duplicated on assignment rather than moved. Integers, floats, bool, char, etc.
5.Control Flow
if, match, and loops. Rust control flow is expression-based.
if expression
if/else is an expression that returns a value. No parens around the condition.
match
match exhausts patterns. Each arm is an expression. Patterns, ranges, and guards.
while loop
while is a conditional loop. Repeats while the condition is true.
for loop
for iterates over ranges and iterators. Rust's preferred loop form.
Infinite loop
loop runs forever until break. Can return a value. Supports labels.
break & continue
break exits the loop. continue skips the current iteration. Both work with labels.
if let
if let simplifies matching for a single pattern. Use when only one variant matters.
while let
while let loops while the pattern continues to match. Good for iterator-style draining.
6.Functions
Function definitions, return values, ownership transfer, closures, and generics.
Function definition
fn defines a function. Parameters need type annotations. The body is an expression.
Return value
The last expression is the return value. A semicolon turns it into a statement.
Parameters
Parameters are immutable by default. Destructured patterns. References avoid copying.
Ownership parameters
Pass-by-value moves ownership. Borrowing allows reuse. Return ownership when needed.
Borrow parameters
&T for read-only borrow, &mut T for mutable borrow. Both avoid moving ownership.
Closures
Closures capture environment values. |params| syntax. Can be stored or passed to functions.
Function pointers
fn is a pointer to a regular function. Use the fn(T) -> U type. Closures can coerce to fn.
Generic functions
Generic parameter <T> abstracts types. Optional bounds. Type inference.
7.Strings
&str and String, operations, formatting, parsing, and iteration.
&str & String
&str is a borrowed string slice, String is an owned growable string.
String operations
Push, insert, replace, remove. Methods that mutate a String.
Formatting
format! composes strings. Placeholders and format specifiers. Safe and efficient.
String slicing
&s[a..b] slices by bytes. Must fall on character boundaries, otherwise panic.
String iteration
chars() iterates characters, bytes() iterates bytes, char_indices yields positions.
String parsing
str::parse converts a string into a value. parse::<T>() needs an explicit target type.
Character operations
char methods: case conversion, digit and whitespace checks. Chained with string methods.
String methods
Search, trim, split, predicate methods. Common str methods are chainable.
8.Collections
Vec, HashMap, set types, and iterators.
Vec
Vec<T> is a growable array. Push and remove at will. Pointer on the stack, data on the heap.
Vec operations
Iterate, filter, map, collect. Slice views and ownership of the underlying Vec.
HashMap
HashMap<K, V> stores key/value pairs. Hash-backed and unordered. O(1) lookups.
HashSet
HashSet<T> holds unique elements. Dedupe, intersection, union, difference.
BTree
BTreeMap / BTreeSet keep keys sorted. Iterate in order. Slightly slower than hash.
Iterators
The Iterator trait drives chained adaptors. Lazy evaluation. Consumed methods execute.
VecDeque
VecDeque is a double-ended queue. Efficient push/pop on both ends. Ring buffer.
Nested collections
Combinations of collections. Vec<HashMap>, nested HashMap, multi-dim Vec.
9.Memory & Ownership Extensions
Heap allocation, smart pointers, and shared ownership.
Stack & heap
Stack: fixed size, fast. Heap: dynamic size, allocated. Ownership governs lifetimes.
Box
Box<T> puts a value on the heap. Fixed size, moveable. Required for recursive types.
Rc
Rc<T> is reference-counted shared ownership. Single-threaded. Read-only sharing.
RefCell
RefCell<T> enforces borrow rules at runtime. Interior mutability. Panics on conflict.
Arc
Arc<T> is thread-safe reference counting. Shared ownership across threads. Atomic counter.
Mutex
Mutex<T> provides exclusive access. The guard protects the inner value. Pair with Arc.
Atomic types
AtomicU32 and friends. Lock-free concurrent counters. Ordering memory orders.
Smart pointers
Deref / Drop traits. Implemented by Box / Rc / Arc. Pointer abstraction with cleanup.
10.Traits & Generics
Trait abstraction, implementations, generic bounds, and polymorphism.
trait definition
A trait defines shared behavior. Method signatures. Like an interface.
Implementing a trait
impl Trait for Type implements the trait. Orphan rule: either the trait or type must be local.
Default methods
Trait methods can have default implementations. Override is optional. Calls are dispatched.
trait objects
dyn Trait is dynamic dispatch. Heterogeneous collections. Runtime polymorphism.
Generics
Generic types and functions. T abstracts. Code reuse. Zero-cost via monomorphization.
Trait bounds
T: Trait bounds. where clauses. Combine bounds with +.
impl blocks
impl blocks define associated functions and methods. self / Self. Constructor conventions.
Composition & polymorphism
Rust has no inheritance. Use trait + composition. Default methods play the base-class role.
11.Error Handling
Result, Option, the ? operator, panic, and custom errors.
Result
Result<T, E> returns success or error. Ok / Err variants.
unwrap & expect
unwrap returns the value or panics. expect adds a custom panic message. For debugging.
? operator
? short-circuits error propagation. Err returns early, Ok unwraps and continues.
Implementing Error
The standard Error trait. Display + Debug. Error source chain.
Custom errors
Design custom error types. Enum variants carry context. Classify errors by category.
thiserror
The thiserror derive macro auto-implements Display / Error. Greatly reduces boilerplate.
Option
Option<T> for possibly-missing values. Some / None. Safe access with combinators.
panic
panic! for unrecoverable errors. Crashes and unwinds. Only for bugs.
12.Input / Output
Standard input/output, file reading/writing, and the file system.
Reading input
stdin read_line into a String. trim removes the trailing newline.
Reading files
read_to_string slurps the whole file. Read trait streams bytes.
Writing files
write / append to a file. OpenOptions controls mode. Buffered writing.
File system
Create directories, delete, rename, test existence. Path operations.
BufRead line by line
BufRead for line-by-line reads. lines(), read_line, split.
Output & writing
print! / println! / eprintln!. write! / writeln! to any writer.
Standard streams
stdin / stdout / stderr. Interactive and piped data.
Byte I/O
read into a byte buffer. Stream binary data. write_all writes everything.
13.Common Pitfalls
The most common pitfalls for Rust beginners and the correct way to write them.
Use after move
After a move the original binding is unusable. Borrow or clone to keep ownership.
Borrow conflict
Shared and mutable borrows cannot coexist. Use scope to shorten borrows.
Dangling reference
Returning a reference to a local is dangling. Return an owned value or a proper lifetime.
String concatenation
+ moves its LHS. Repeated + is slow. Prefer format! or push_str.
Index type
Indices and lengths are usize, not i32. Type mismatch when indexing collections.
match arm types
All match arms must return the same type. Missing variants need a _ wildcard.
Closure capture
Closures borrow or move automatically as needed. Conflicts arise. move explicit-transfers.
Integer overflow
Debug builds panic on overflow. Release builds wrap. Handle explicitly or choose a wider type.
14.Concurrency
Threads, channels, shared state, and Send/Sync.
Threads
thread::spawn launches a thread. join waits and returns the result.
move closures
move closures transfer captures into the thread. Avoids dangling borrows.
channel
mpsc is multi-producer single-consumer. send / recv pass data. Type-safe.
Multiple producers
Clone the Sender for multiple producers. One shared receiver.
Shared mutability
Arc<Mutex<T>> shares mutable data across threads. The lock guards access.
scoped threads
thread::scope lets threads borrow non-'static data. No move required.
rayon parallel
rayon parallel iterators. par_iter replaces iter. Easy data parallelism.
Send & Sync
Send: safe to move across threads. Sync: safe to share behind &T. Compiler-checked.
15.Networking
TCP, UDP, HTTP, and third-party networking crates.
TCP connect
TcpStream connects. read / write exchange bytes. Stream-oriented protocol.
TCP listen
TcpListener binds and accepts. Handle each connection, often in a thread.
HTTP request
reqwest makes HTTP calls. JSON requests and responses.
HTTP server
axum builds HTTP services. Routes and handlers. Async by default.
URL handling
The url crate parses and builds URLs. Query parameters.
IP parsing
std::net::IpAddr parses IPs. Distinguish IPv4 vs IPv6.
UDP
UdpSocket is connectionless datagrams. send_to / recv_from. No handshake.
DNS resolution
ToSocketAddrs resolves hostnames. Yields an iterator of addresses.
16.Time & Date
SystemTime, Instant, Duration, and chrono.
SystemTime
SystemTime is the system wall clock. Get now and compare against UNIX_EPOCH.
Instant timing
Instant is a monotonic clock for elapsed time. Immune to system clock changes.
Duration
Duration is a span of time. Seconds / nanosecond precision. Arithmetic & conversions.
chrono current time
chrono handles date-times. Utc / Local time zones. Human readable.
Formatted output
format outputs a date-time. strftime-style placeholders.
Parsing strings
DateTime::parse_from_str parses strings. ISO 8601 parsing supported.
Time arithmetic
Add/subtract time spans, compute differences, range checks.
Time zone handling
FixedOffset represents a fixed time zone. Convert across zones via with_timezone.
17.Process & Environment
Command-line arguments, environment variables, child processes, and paths.
Arguments & environment
std::env reads args and environment variables. args and var.
clap argument parsing
clap parses CLI arguments. Subcommands, options, auto-generated help.
std::process
Exit codes, Command for child processes, current process info.
Command child process
Command controls child processes. Args, env, pipes, capture output.
PathBuf
Path / PathBuf manipulate paths. Join, components, canonicalize. Cross-platform.
Working directory
Current directory, change directory, user home. Path-related helpers.
Directory traversal
read_dir lists a directory. Recurse manually. Filter by entry type.
Signal handling
The ctrlc crate catches Ctrl-C. Graceful shutdown, resource cleanup.
18.Regular Expressions
The regex crate for matching, capturing, replacing, and splitting.
Compile regex
Regex::new compiles a regex. Use raw strings r#... Reuse compiled regexes.
Match check
is_match tests for any match. Use anchors for whole-string matching.
Capture groups
Capture groups extract substrings. captures returns the matches. Named groups supported.
Find all
find_iter walks every match. captures_iter yields all matches with groups.
Replace
replace swaps matches. $1 references groups. replace_all replaces every match.
Split
split by regex. splitn limits the number of pieces.
Common patterns
Common regex recipes: email, URL, phone, IP. Character classes.
Flags & case
(?i) inline flags like ignore-case. RegexBuilder for more control.
19.Build & Test
cargo build, unit tests, linting, and release configuration.
cargo build
Build the project. Debug / release profiles. Output paths. Incremental compilation.
Unit tests
#[test] attribute. cargo test runs them. Assertion macros.
Doc tests
Doc comments can run as tests. cargo test verifies them. Integration tests live in tests/.
Dependency management
Cargo.toml declares dependencies. Semver. cargo update.
clippy lint
cargo clippy lints code. Catches potential bugs and style issues.
Code formatting
cargo fmt applies rustfmt. Consistent style across the team.
Release configuration
[profile.release] tweaks optimization. Strip, LTO, panic behavior.
Documentation generation
cargo doc generates API docs. rustdoc markup. Run doc tests before release.
Official Links
Direct links to the official docs and resources.
About this Cheatsheet
This page is a self-contained Rust 2021 cheatsheet — covering the language core and the most common std APIs that handle about 80% of everyday usage in real projects. The content favors modern idioms: ? for error propagation, exhaustive match, iterators over hand-written loops, and a clear distinction between String and &str. For authoritative references see the official Rust Book and the standard library docs. The 19 sections each focus on one topic — from your first program to ownership, traits, concurrency, and common pitfalls. Each section is broken into 8 example-driven subtopics (5–20 lines each), totalling roughly 150 topics. The code snippets are deliberately short and self-explanatory. Everything runs in your browser — nothing is uploaded, nothing is tracked. This page is part of GuruToolkit's free developer toolset; the snippets here are free to use with no warranty.
Version 2.1.0