Rust Reference
Free reference guide: Rust Reference
About Rust Reference
This Rust Reference is a searchable cheat sheet organized into eight categories — Basics, Ownership, Structs, Enums, Traits, Error Handling, Concurrency, and Macros — covering the language features you use in every Rust project. Each entry includes copy-ready code that compiles with the latest stable Rust toolchain, so you can paste directly into your editor and build immediately.
Rust stands apart from other systems languages through its ownership model, which guarantees memory safety at compile time without a garbage collector. This reference devotes an entire category to ownership, borrowing (&, &mut), lifetimes, cloning, and slices, reflecting how central these concepts are to writing correct Rust programs. Understanding the borrow checker is the steepest part of the Rust learning curve, and having concrete examples at hand accelerates that process significantly.
Beyond memory management, the reference covers Rust's expressive type system — structs with impl blocks, enums that carry data (Option<T>, Result<T, E>), trait definitions and bounds, and the ? operator for ergonomic error propagation. Concurrency entries demonstrate thread::spawn, Mutex<T> with Arc, MPSC channels, and async/await, giving you the building blocks for both threaded and asynchronous Rust applications.
Key Features
- Ownership & borrowing section covering move semantics, immutable/mutable references, clone, lifetimes, and slices
- Pattern matching with match, if let, and while let including range and multi-value arm syntax
- Struct definitions with impl methods, tuple structs, and #[derive] for Debug, Clone, PartialEq
- Enum variants with data payloads, plus detailed Option<T> and Result<T, E> usage patterns
- Trait system coverage — definition, implementation, trait bounds, where clauses, and dyn Trait objects
- Error handling patterns using the ? operator, unwrap/expect, custom error enums, and panic!
- Concurrency primitives — thread::spawn, move closures, Arc<Mutex<T>>, mpsc channels, and async/await
- Macro examples including vec!, macro_rules!, iterator chaining with filter/map/sum, and collect turbofish syntax
Frequently Asked Questions
What Rust edition does this reference target?
All examples follow the Rust 2021 edition conventions and compile with stable Rust 1.70+. No nightly-only features are used, so you can run every example with rustc or cargo on any recent stable toolchain.
What is ownership in Rust and why does it matter?
Ownership is Rust's core mechanism for memory safety. Every value has exactly one owner, and when the owner goes out of scope the value is dropped. Moving a value transfers ownership, preventing use-after-free bugs. Borrowing (&, &mut) lets you reference data without taking ownership, subject to the rule that you can have either one mutable reference or any number of immutable references at a time.
When should I use String vs &str?
Use &str (a string slice) when you only need to read string data and do not need to own or modify it — it is a borrowed view into a String or a string literal. Use String when you need heap-allocated, growable, owned string data, such as when building strings dynamically or storing them in structs.
How do Option<T> and Result<T, E> relate to error handling?
Option<T> represents a value that may or may not exist (Some(T) or None), replacing null pointers. Result<T, E> represents an operation that may succeed (Ok(T)) or fail (Err(E)). Both integrate with match and the ? operator for concise, type-safe error propagation without exceptions.
What is the difference between a trait and an interface?
Rust traits are similar to interfaces in other languages but more powerful. Traits can provide default method implementations, be used as generic bounds, and work with dynamic dispatch via dyn Trait. Unlike interfaces, traits can be implemented for types you don't own (orphan rule permitting) and support associated types and constants.
How does Rust handle concurrency safely?
Rust's type system enforces thread safety at compile time. The Send trait marks types safe to transfer between threads, and Sync marks types safe to share. Combined with ownership rules, this prevents data races. Shared mutable state requires explicit synchronization (Arc<Mutex<T>>), and the compiler rejects code that violates these constraints.
What is the ? operator and how does it simplify error handling?
The ? operator is syntactic sugar for unwrapping Result or Option values. If the value is Ok(v) or Some(v), it unwraps to v; if it is Err(e) or None, the function returns early with the error. This replaces nested match blocks with clean, linear code, and works only in functions whose return type is Result or Option.
How are macros different from functions in Rust?
Macros operate at compile time on syntax tokens, while functions operate at runtime on values. macro_rules! macros use pattern matching on token trees to generate code, enabling variable argument counts (like vec![1,2,3]) and compile-time code generation that functions cannot achieve. Procedural macros (derive, attribute) provide even more power for metaprogramming.