Rust Reference
Every Rust keyword, operator, standard library type, trait, macro and tool in one place: concise, accurate pages with live examples that compile and run on Rust 1.99 (edition 2024), with signatures, panics and complexity.
Keywords and Statements
-
letVariable bindings, shadowing and let-else. -
mutMutable bindings and mutable references. -
constCompile-time constants and const items. -
staticGlobal variables with a fixed address. -
if and elseConditional expressions, if let and let chains. -
matchExhaustive pattern matching. -
loopInfinite loops, break with a value and labels. -
whileCondition-controlled loops and while let. -
forIterating over anything that implements IntoIterator. -
break and continueLeaving or skipping iterations, with labels. -
returnReturning early from a function. -
fnDefining functions and function pointer types. -
structNamed, tuple and unit structs. -
enumEnums with data in their variants. -
unionUntagged unions for FFI and low-level code. -
implInherent and trait implementations. -
traitDefining shared behavior. -
typeType aliases and associated types. -
whereTrait bounds in where clauses. -
dynTrait objects and dynamic dispatch. -
modDeclaring modules. -
useBringing names into scope. -
pubVisibility: pub, pub(crate), pub(super), pub(in path). -
crate, self and superPath prefixes for navigating modules. -
externextern crate, extern "C" and foreign functions. -
unsafeUnsafe blocks, functions, traits and impls. -
async and awaitAsync functions, blocks and awaiting futures. -
moveMove closures and captured ownership. -
refBinding by reference in patterns. -
asPrimitive casts and use-renaming. -
inThe in keyword inside for loops. -
Self and selfThe current type and the method receiver. -
Reserved keywordsabstract, become, box, do, final, gen, try and more. -
Raw identifiers (r#)Using keywords as identifiers.
Primitive Types
-
i8 to i128, isizeSigned integer types, ranges and methods. -
u8 to u128, usizeUnsigned integer types, ranges and methods. -
Integer methodschecked_, wrapping_, saturating_, overflowing_ and pow. -
f32 and f64Floating-point types and their methods. -
NaN, infinity and total_cmpFloating-point special values and ordering. -
boolBooleans and their methods. -
charUnicode scalar values. -
strString slices and their methods. -
[T; N] arraysFixed-size arrays. -
[T] slicesThe slice type and borrowing parts of arrays and vectors. -
TuplesFixed-size heterogeneous groups. -
() unitThe empty tuple and the unit type. -
! never typeFunctions that never return. -
&T and &mut TShared and exclusive references. -
*const T and *mut TRaw pointers and their methods. -
fn pointersFunction pointer types. -
Range typesRange, RangeInclusive and friends. -
NonZero integersNonZeroU32 and niche optimization. -
Wrapping and SaturatingInteger wrapper types with fixed overflow behavior.
Operators and Expressions
-
Arithmetic operators+, -, *, / and % with overflow behavior. -
Comparison operators==, !=, <, >, <= and >= and the traits behind them. -
Logical operators&&, || and !. -
Bitwise operators&, ^, !, << and >> on integers, plus the or operator. -
Compound assignment+=, -=, <<= and the other assignment operators. -
? operatorPropagating errors and None. -
.. and ..=Range expressions and slicing. -
* dereferenceDereferencing references and smart pointers. -
& and &mutTaking references. -
as castsNumeric and pointer casts. -
[] indexingIndex and IndexMut. -
. member accessField access, method calls and auto-deref. -
::<> turbofishSpecifying generic arguments explicitly. -
Closure syntaxClosure expressions and capture modes. -
Operator precedencePrecedence and associativity table. -
Block expressionsBlocks, labeled blocks and const blocks. -
Struct update syntax..base in struct expressions.
Patterns
-
Literal and identifier patternsMatching values and binding names. -
_ and .. patternsIgnoring values and the rest of a collection. -
Range patterns1..=5 and 'a'..='z' in patterns. -
DestructuringTaking apart structs, tuples and enums. -
Slice patternsMatching arrays and slices by shape. -
Or-patterns and match guardsAlternatives in one arm and extra if conditions. -
@ bindingsNaming a value while testing it. -
Reference patterns&x, ref and matching through references. -
if let, while let and let-elseRefutable patterns in control flow. -
matches! patternsQuick boolean pattern checks.
Option and Result
-
Option<T>An optional value: Some or None. -
Option unwrap familyunwrap, expect, unwrap_or and unwrap_or_else. -
Option map and and_thenTransforming optional values. -
Option filter, or and xorCombining and filtering options. -
Option take and replaceMoving values out of an Option in place. -
Option as_ref, as_mut, as_derefBorrowing the contents of an Option. -
Option ok_or and ok_or_elseConverting an Option into a Result. -
Option zip, flatten and transposeCombining nested options. -
Result<T, E>Success or failure: Ok or Err. -
Result unwrap familyunwrap, expect, unwrap_or and unwrap_err. -
Result map, map_err, and_thenTransforming results. -
Result ok, err and is_okConverting results to options and testing them. -
Collecting ResultsTurning an iterator of Results into a Result of a collection.
Strings and Text
-
StringThe growable, owned UTF-8 string. -
String::new, from, with_capacityCreating strings. -
push, push_str and insertAppending and inserting text. -
pop, remove, truncate, clearRemoving text from a String. -
len, is_empty and capacityMeasuring strings. -
split, rsplit and splitnSplitting a string. -
split_whitespace, lines, split_onceMore splitting helpers. -
trim and strip_prefixRemoving whitespace and prefixes. -
find, contains, starts_withSearching in a string. -
replace and replacenReplacing substrings. -
to_uppercase and to_lowercaseChanging case. -
chars, char_indices, bytesIterating over text. -
parse and FromStrConverting text to other types. -
String slicing and char boundariesByte ranges, get and is_char_boundary. -
repeat, concat and joinBuilding strings from pieces. -
from_utf8 and from_utf8_lossyConverting bytes to text. -
as_bytes, into_bytes, encode_utf8Looking at the UTF-8 bytes. -
CString and CStrC-compatible strings. -
OsString and OsStrPlatform strings. -
char methodsis_alphabetic, to_digit, from_u32 and more.
Collections
-
Vec<T>The growable array. -
Vec::new, push, popCreating and growing vectors. -
Vec insert, remove, swap_removeChanging elements by position. -
Vec retain, dedup, drainFiltering vectors in place. -
Vec extend, append, split_offCombining vectors. -
Vec capacity and reserveControlling allocation. -
sort, sort_by and sort_unstableSorting slices. -
binary_search and partition_pointSearching sorted slices. -
windows, chunks and splitWalking slices in groups. -
swap, reverse and rotateRearranging slice contents. -
first, last and split_atGetting parts of a slice. -
copy_from_slice, fill, to_vecCopying and filling slices. -
VecDeque<T>Double-ended queue. -
LinkedList<T>Doubly linked list. -
HashMap<K, V>Hash table. -
HashMap insert, get, removeBasic map operations. -
HashMap entry APIor_insert, and_modify and friends. -
HashMap iterationkeys, values, iter and drain. -
HashSet<T>Unique values with fast lookup. -
HashSet union, intersection, differenceSet algebra. -
BTreeMap<K, V>Sorted map. -
BTreeMap range and first/lastOrdered queries. -
BTreeSet<T>Sorted set. -
BinaryHeap<T>Priority queue. -
Array methodsmap, iter, as_slice, from_fn and more. -
Hash, Hasher and RandomStateHashing and custom hashers.
Smart Pointers and Memory
-
Box<T>Heap allocation and Box<dyn Trait>. -
Rc<T>Single-threaded reference counting. -
Weak<T>Non-owning references that break cycles. -
Arc<T>Atomic reference counting for threads. -
Cell<T>Interior mutability for Copy types. -
RefCell<T>Runtime-checked borrowing. -
OnceCell and LazyCellSingle-threaded lazy initialization. -
Cow<'a, B>Clone on write. -
Pin<P>Values that must not move. -
ManuallyDrop and MaybeUninitControlling initialization and drop. -
PhantomData<T>Marker for unused type parameters. -
std::memswap, replace, take, size_of, drop and forget. -
std::ptrNonNull, null, read, write and copy. -
std::allocLayout and the global allocator.
Core Traits
-
CloneExplicit duplication. -
CopyImplicit bitwise copies. -
DebugDeveloper-facing formatting and #[derive(Debug)]. -
DisplayUser-facing formatting. -
DefaultDefault values. -
PartialEq and EqEquality comparison. -
PartialOrd and OrdOrdering and sorting. -
HashHashing values for maps. -
From and IntoInfallible conversions. -
TryFrom and TryIntoFallible conversions. -
AsRef and AsMutCheap reference conversions. -
Borrow and ToOwnedBorrowed forms of owned data. -
Deref and DerefMutSmart pointer dereferencing. -
DropCleanup when a value goes out of scope. -
FromStrParsing from text. -
ToStringConverting to String via Display. -
Add, Sub, Mul, Div, Rem, NegArithmetic operator traits. -
BitAnd, BitOr, BitXor, Not, Shl, ShrBitwise operator traits. -
AddAssign and friendsCompound assignment traits. -
Index and IndexMutOverloading []. -
Fn, FnMut and FnOnceThe closure traits. -
Send and SyncThread-safety marker traits. -
Sized and ?SizedStatically sized and dynamically sized types. -
UnpinTypes that can move after pinning. -
AnyRuntime type identification. -
std::error::ErrorThe standard error trait. -
Extend and FromIteratorBuilding collections from iterators. -
Sum and ProductReducing iterators to one number. -
fmt::WriteWriting formatted text into strings. -
TerminationWhat main may return.
Iterators
-
IteratorThe iterator trait and next(). -
IntoIteratorTypes that can be iterated. -
DoubleEndedIteratorIterating from both ends. -
ExactSizeIteratorIterators with a known length. -
map and filterTransforming and selecting items. -
filter_map and flat_mapCombined mapping and flattening. -
enumerate and zipPairing items with indexes or other iterators. -
take, skip, step_byLimiting and striding. -
take_while, skip_while, map_whileConditional prefixes. -
chain, cycle, once, repeatCombining and repeating iterators. -
fold, reduce, try_foldAccumulating values. -
collectBuilding collections from iterators. -
sum, product, countCounting and totaling. -
min, max, min_by_keyFinding extremes. -
any, all, find, positionSearching and testing. -
peekableLooking one item ahead. -
rev and lastReversing iterators. -
scan, inspect, fuseStateful and debugging adapters. -
partition and unzipSplitting iterators into collections. -
cmp, eq, lt, is_sortedComparing iterators. -
from_fn, successors, repeat_withCreating iterators from closures. -
by_ref, iter, iter_mut, into_iterBorrowing and consuming iterators.
Macros
-
println! and print!Printing to standard output. -
eprintln! and eprint!Printing to standard error. -
format!Building a String from a format string. -
write! and writeln!Writing formatted text to any writer. -
Format specifiersWidth, precision, alignment, fill, hex and more. -
vec!Creating vectors. -
panic!Aborting the current thread with a message. -
assert!, assert_eq!, assert_ne!Runtime checks that panic. -
debug_assert!Checks that only run in debug builds. -
unreachable!, todo!, unimplemented!Marking code paths. -
matches!Boolean pattern test. -
dbg!Quick debugging output. -
concat!, stringify!, line!, file!Compile-time text macros. -
env!, option_env! and include_str!Reading compile-time data. -
cfg! and compile_error!Compile-time conditions. -
thread_local!Declaring thread-local variables. -
macro_rules!Declarative macros. -
Macro fragment specifiersexpr, ident, ty, tt, pat and more. -
Macro repetitions$(...)*, $(...),+ and nesting. -
Procedural macrosDerive, attribute and function-like macros.
Attributes
-
#[derive]Generating trait implementations. -
#[cfg] and cfg_attrConditional compilation. -
#[test] and #[should_panic]Unit tests. -
#[ignore]Skipping tests and running them on demand. -
#[allow], #[warn], #[deny], #[expect]Controlling lints. -
#[inline]Inlining hints. -
#[must_use]Warning on ignored results. -
#[deprecated]Marking APIs as deprecated. -
#[repr]Choosing data layout. -
#[non_exhaustive]Preventing exhaustive matching on public types. -
#[no_mangle] and #[export_name]Exporting symbols for FFI. -
#[doc] and doc commentsDocumentation attributes. -
#![no_std], #![no_main], #![feature]Crate-level attributes. -
#[cold], #[track_caller]Optimizer and panic-location hints. -
#[global_allocator]Replacing the allocator. -
Common lintsdead_code, unused_variables and more.
Standard Library Modules
-
std::fmtFormatter, Debug builders and Arguments. -
std::fsReading and writing files and directories. -
std::ioRead, Write, BufRead and stdin/stdout. -
std::pathPath and PathBuf. -
std::envArguments, environment variables and the current directory. -
std::processCommand, exit and Child. -
std::threadSpawning and joining threads. -
std::syncMutex, RwLock, Condvar, Barrier and Once. -
std::sync::mpscChannels. -
std::sync::atomicAtomic types and memory ordering. -
std::timeDuration, Instant and SystemTime. -
std::netTCP, UDP and IP addresses. -
std::collectionsOverview of the collection types. -
std::iterIterator constructors and traits. -
std::cmpOrdering, min, max, Reverse. -
std::convertConversion traits and Infallible. -
std::opsOperator traits and range types. -
std::errorThe Error trait and Box<dyn Error>. -
std::numParseIntError, NonZero and Wrapping. -
std::charchar conversion functions. -
std::hashHash, Hasher and BuildHasher. -
std::any and std::markerType information and marker traits. -
std::paniccatch_unwind, set_hook and Location. -
std::future and std::taskFuture, Poll, Context and Waker. -
std::ffi and std::osInteroperability with C and the OS. -
The preludeWhat is in scope without imports. -
DurationSpans of time. -
Instant and SystemTimeMeasuring and reading time. -
Mutex<T>Mutual exclusion. -
RwLock<T>Many readers or one writer. -
CondvarWaiting for a condition. -
OnceLock and LazyLockThread-safe lazy initialization. -
AtomicUsize, AtomicBool and friendsLock-free counters and flags. -
OrderingComparison result. -
File and OpenOptionsOpening files. -
BufReader and BufWriterBuffered I/O. -
PathBuf and PathWorking with paths. -
CommandSpawning processes. -
TcpListener and TcpStreamTCP networking. -
IpAddr and SocketAddrNetwork addresses. -
thread::scopeScoped threads that borrow locals.
Errors, Panics and Process
-
Error handling overviewOption, Result, panic and when to use each. -
Box<dyn Error>A catch-all error type. -
Writing a custom error typeError enums with Display and From. -
Panic, unwind and abortWhat a panic does. -
Exit codes and main returning ResultProcess results. -
Parse and conversion errorsParseIntError, ParseFloatError and TryFromIntError. -
io::Error and ErrorKindI/O failures.
Tools
-
rustcThe compiler and its flags. -
cargo new and cargo initCreating projects. -
cargo build and cargo runBuilding and running. -
cargo checkFast type-checking. -
cargo testRunning tests. -
cargo add, remove and updateManaging dependencies. -
cargo docGenerating documentation. -
cargo fmtFormatting code. -
cargo clippyThe linter. -
cargo publish and packageReleasing crates. -
cargo tree and metadataInspecting dependencies. -
cargo installInstalling binaries. -
cargo benchBenchmarking. -
rustupToolchain manager. -
Cargo.tomlPackage manifest fields. -
Cargo profiles and featuresOptimization levels and optional features. -
Cargo workspacesMultiple crates in one repo. -
rustfmt.tomlFormatter configuration. -
rustdocDocumentation tool and doctests. -
MiriDetecting undefined behavior. -
Editions2015, 2018, 2021, 2024 differences.
Concepts
-
Ownership rulesMoves, copies and drops. -
Borrowing rulesShared versus exclusive references. -
LifetimesAnnotations and elision rules. -
Move versus copyWhich types are Copy. -
Stack and heapWhere values live. -
Generics and monomorphizationCompile-time specialization. -
Static versus dynamic dispatchimpl Trait, generics and dyn. -
impl TraitIn argument and return position. -
Closures and captureHow closures capture variables. -
Interior mutabilityCell, RefCell, Mutex and friends. -
ShadowingRedeclaring names. -
Integer overflowDebug panics and release wrapping. -
Deref and unsized coercionsAutomatic type adjustments. -
Orphan and coherence rulesWhere trait impls may live. -
Modules and pathsVisibility, use and file layout. -
Concurrency modelsThreads, channels, locks and async. -
Async RustFutures, executors and why std has no runtime. -
Unsafe RustThe five unsafe superpowers. -
FFI with Cextern "C", repr(C) and strings. -
no_std programmingcore and alloc. -
Choosing a conversionas, From, TryFrom, parse and to_string. -
Naming conventionsCase rules and API guidelines. -
Rust versus C++ and JavaMapping familiar concepts.
Nothing matches โโ. Try the site search.