Rust Concept Index

Short definitions of concepts related to Rust, each with links to where they are explained in depth: the library books, the standard library API docs, and the rustmax crates.

Ownership and borrowing: Ownership · Moves · Borrowing · Lifetimes · Lifetime elision · The static lifetime · Copy and Clone · Drop and resource management · Slices

Types: Structs and enums · Option · Strings · Smart pointers · Interior mutability · Clone-on-write · Dynamically sized types · Zero-sized types · PhantomData · The never type · Type layout

Traits and generics: Traits · Generics · Trait bounds · Trait objects · impl Trait · Associated types · Generic associated types · Const generics · Higher-ranked trait bounds · Marker traits · Blanket implementations · Coherence and the orphan rule · Conversion traits · Operator overloading · Deref coercion

Expressions and control flow: Pattern matching · let else · Closures · Iterators · Type inference · Turbofish

Error handling: Result · The question mark operator · The Error trait · Panics

Unsafe and FFI: Unsafe Rust · Undefined behavior · Raw pointers · FFI · no_std

Concurrency and async: Threads · Send and Sync · Shared state · Atomics · Channels · Data parallelism · Async and await · Async runtimes · Pinning

Code organization: Crates and packages · Modules and visibility · Preludes · Workspaces · Features · Conditional compilation · Attributes · Declarative macros · Procedural macros · Build scripts · Editions · Semantic versioning

Idioms and patterns: Newtype · Builder · Typestate · Extension traits · Sealed traits · The entry API · Lazy initialization

Internals: Monomorphization · Zero-cost abstractions · The borrow checker · Variance · Specialization

Ownership and borrowing

Ownership

Every value has exactly one owner, a variable or another value, and is destroyed when its owner goes out of scope. Programmers do not need to free memory manually, and Rust does not need a garbage collector.

Books: TRPL 4.1, Nomicon: Ownership

Moves

Assigning a value or passing it to a function moves it, transferring ownership. The old binding can no longer be used. A move is a shallow memcpy at most, and frequently optimized away.

Books: TRPL 4.1, Reference: Moved and copied types

Borrowing

A reference, &T or &mut T, uses a value without taking ownership of it. At any moment a value may have any number of shared & borrows or exactly one &mut borrow, never both. One can think of &mut as “exclusive” rather than “mutable”. The mutability is a benefit of having exclusive access.

Books: TRPL 4.2, Nomicon: References

Lifetimes

A lifetime is the region of code over which a reference is valid, written 'a. Lifetime annotations never change how long anything lives. They describe relationships between references so the compiler can check them.

Books: TRPL 10.3, Nomicon: Lifetimes

Lifetime elision

Rules that let most function signatures omit lifetimes. With exactly one input reference, the output borrows from it. In a method, the output borrows from self. Elision rules reflect the most common lifetime patterns. When elision produces incorrect restrictions it results in compilation failures. Write the lifetimes out then.

Books: Reference: Lifetime elision, Nomicon: Lifetime elision

The static lifetime

'static means “can live for the rest of the program”, not “lives for the rest of the program”. As a bound, T: 'static means the type holds no non-static borrows, so owned types like String satisfy it.

Books: TRPL 10.3

Copy and Clone

Clone is an explicit, possibly expensive, duplication: x.clone(). Copy marks types where a bitwise copy is enough, so they are copied instead of moved. A type can be Copy only if all its fields are Copy and it has no Drop implementation.

Books: TRPL Appendix C
std: Copy, Clone

Drop and ownership-based resource management

When a value goes out of scope its Drop implementation runs, then its fields are dropped in declaration order. Resources such as files, locks, and sockets are released this way. This pervasive behavior is what C++ calls (confusingly) “resource acquisition is initialization”.

Books: TRPL 15.3, Reference: Destructors, Nomicon: OBRM
std: Drop, std::mem

Slices

A slice, [T], is a view into a contiguous run of elements. It is dynamically sized, and almost always used behind a reference as &[T] or &mut [T], which are also conventionally called slices. Likewise &str is a string slice, a reference to the unsized str slice. Take slices as function parameters rather than &Vec<T> or &String, each of which automatically dereferences to a slice.

Books: TRPL 4.3, Reference: Slice types
std: std::slice

Types

Structs and enums

Structs group fields together. Enums choose between variants, each of which can carry its own data. Enums are sum types, and together with structs they make up Rust’s algebraic data types. They are the idiomatic way to model a value that is one of several shapes, and match forces every shape to be handled.

Books: TRPL 5, TRPL 6, Reference: Enumerations

Option

The Option<T> enum is either Some(T) or None. Rust uses it where other languages use null. Its combinators, like map, and_then, unwrap_or, and ok_or, are core Rust vocabulary.

Books: TRPL 6.1
std: std::option

Strings

String is an owned, growable, UTF-8 buffer. &str is a borrowed view of one. Strings can’t be indexed by integer because a Unicode character may be several bytes. OsString and PathBuf hold platform strings that may not be UTF-8, and CString holds the NUL-terminated strings C expects.

Books: TRPL 8.2
std: std::string, std::str, std::ffi

Smart pointers

Types that own a value through a pointer and add behavior. Box<T> puts a value on the heap with a single owner. Rc<T> and Arc<T> add shared ownership through reference counting, Arc being the thread-safe one. Cycles of Rc and Arc leak. Break them with Weak.

Books: TRPL 15
std: Box, std::rc, Arc

Interior mutability

Mutating through a shared & reference, with the exclusivity rule checked at runtime or made unnecessary statically. Cell moves values in and out without ever handing out a reference, so it needs no runtime checks. RefCell checks borrows at runtime. Mutex, RwLock, and atomics do the same across threads. Rc<RefCell<T>> is a common combination that produces shared mutable data structures like in many other languages. It is a pattern that works against the strengths of Rust’s type system and its presence can be a hint that the code could be restructured to be more idiomatic and possibly more performant.

Books: TRPL 15.5, Reference: Interior mutability
std: std::cell

Clone-on-write

Cow<'a, T> holds either a borrowed or an owned value, cloning only when it has to be modified or kept. It suits functions that usually return their input unchanged but sometimes have to build something new.

std: Cow

Dynamically sized types

Types whose size is only known at runtime: str, [T], and dyn Trait. They only exist behind a “fat” pointer that carries a length or vtable. Generic parameters are implicitly Sized. Write T: ?Sized (“maybe sized”) to accept these types too.

Books: Reference: Dynamically sized types, Nomicon: Exotic sizes
std: Sized

Zero-sized types

Types with no data, such as (), unit structs, and PhantomData, take up no memory at all. A HashMap<K, ()> is effectively a HashSet<K>, with no wasted space.

Books: Nomicon: Exotic sizes

PhantomData

A zero-sized marker that makes a type act as if it owned a T without storing one. Use it when a type parameter appears only in the meaning of a type, such as typed IDs or handles to foreign data, so lifetime variance is analyzed correctly. In safe code the compiler will tell you when you need this.

Books: Nomicon: PhantomData
std: PhantomData

The never type

! is the type of expressions that never produce a value, like panic!(), loop {}, return, continue. It is also the return type of functions that never return, e.g. by panicking or looping forever. It coerces to any type, which is why let x: u32 = todo!(); compiles.

Books: Reference: Never type, TRPL 20.3

Type layout

By default the compiler is free to reorder and pad struct fields. #[repr(C)] fixes the layout to match C, and #[repr(transparent)] guarantees a wrapper has its single field’s layout.

Books: Reference: Type layout, Nomicon: repr(Rust), Nomicon: Alternative representations
std: std::mem

Traits and generics

Traits

A trait is a set of methods a type can implement, and is Rust’s main tool for abstraction and code sharing. A trait’s methods can only be called where the trait is in scope. Crates that are heavily generic often provide a prelude to import many traits at a time.

Books: TRPL 10.2, Reference: Traits

Generics

Functions and types parameterized over other types, fn max<T: Ord>(...). Generic code is compiled separately for each concrete type it is used with, called monomorphization.

Books: TRPL 10.1, Reference: Generic parameters

Trait bounds

Constraints on generic parameters, T: Display + Clone, written inline or in a where clause. A bound grants a capability. Inside the function you can only use what the bounds promise.

Books: TRPL 10.2, Reference: Trait and lifetime bounds

Trait objects

dyn Trait is a value of some unknown type implementing Trait, called through a vtable, usually as Box<dyn Trait> or &dyn Trait. Use trait objects to hold collections of heterogeneous types, or to reduce compile times and the syntactic overhead of generics when ultimate performance is not necessary. Not every trait can be made into an object, and traits that can be are called “dyn compatible”, formerly “object safe”.

Books: TRPL 18.2, Reference: Trait objects

impl Trait

In argument position, impl Trait is shorthand for a generic parameter. In return position, it returns one concrete type without naming it, which is how functions return closures and iterator chains.

Books: TRPL 10.2, Reference: Impl trait type

Associated types

A type chosen by each implementation of a trait, like Iterator::Item. A trait with a generic parameter, Iterator<T>, could be implemented many times for one type, once per T. With an associated type there is only one implementation, so Item is determined by the implementing type and callers never have to specify it.

Books: TRPL 20.2, Reference: Associated items

Generic associated types

Associated types with their own generic or lifetime parameters, type Item<'a> where Self: 'a;. They make “lending” iterators and similar borrowed-view APIs expressible.

Books: Reference: Associated items, RFC 1598

Const generics

Generic parameters that are values rather than types, most often array lengths: struct Matrix<const N: usize>. This is what lets arrays of any length implement traits.

Books: Reference: Generic parameters, RFC 2000

Higher-ranked trait bounds

for<'a> F: Fn(&'a T) says a bound holds for every lifetime, not just one chosen by the caller. They are mostly written for you by elision in Fn bounds, and show up by name in error messages about closures.

Books: Nomicon: HRTB, Reference: Trait and lifetime bounds

Marker traits

Traits with no methods that describe a property of a type: Copy, Sized, Send, Sync, Unpin. Several are “auto traits”, implemented automatically when all of a type’s fields implement them.

Books: Reference: Special types and traits
std: std::marker

Blanket implementations

An impl<T: Display> ToString for T implements a trait for every type meeting a bound at once. They are powerful, but each one rules out many other implementations, restricting other crates’ ability to implement the trait.

Books: TRPL 10.2, Reference: Implementations

Coherence and the orphan rule

There must be at most one implementation of a trait for a type. To guarantee this across crates, you may only implement a trait if either the trait or the type is defined in your crate. Work around it with a newtype or an extension trait.

Books: Reference: Implementations, TRPL 20.2, RFC 1023

Conversion traits

From and Into for infallible conversions, TryFrom and TryInto for fallible ones, AsRef for cheap reference-to-reference conversions, and Borrow when the borrowed form must hash and compare identically. Implement From and you get Into for free.

Books: API Guidelines: Interoperability
std: std::convert, Borrow
Crates: derive_more

Operator overloading

Operators are sugar for trait methods: a + b calls Add::add, a[i] calls Index::index, a == b calls PartialEq::eq. Implement the traits to give your types operators.

Books: TRPL 20.2, Reference: Operator expressions
std: std::ops, std::cmp

Deref coercion

When a &T is expected and a &U is given, the compiler inserts Deref calls until the types match, so a &String passes as &str and a &Box<T> as &T. Method calls auto-deref the same way. Implementing Deref on non-pointer types to imitate inheritance is discouraged.

Books: TRPL 15.2, Reference: Type coercions, Nomicon: The dot operator
std: Deref

Expressions and control flow

Pattern matching

Patterns destructure values and test their shape, in match, if let, while let, let, and function parameters. match must be exhaustive, covering every possible value.

Books: TRPL 6.2, TRPL 19, Reference: Patterns

let else

let Some(x) = opt else { return; }; binds on a match and diverges otherwise. This exists entirely to avoid the unwieldy indentation imposed by a match over a single case.

Books: Reference: Statements, RFC 3137

Closures

Anonymous functions that capture variables from their environment, |x| x + offset. Each closure has its own unnameable type implementing Fn, FnMut, or FnOnce depending on how it uses its captures. A move before the arguments makes the closure take ownership of what it captures, which thread::spawn usually requires.

Books: TRPL 13.1, Reference: Closure expressions
std: Fn

Iterators

Lazy sequences driven by next(), transformed with adapters like map, filter, and zip, and consumed by collect or sum. Iterator chains usually compile to the same code as a hand-written loop. for loops call IntoIterator::into_iter, so for x in &v, for x in &mut v, and for x in v are equivalent to iterating v.iter(), v.iter_mut(), and v.into_iter().

Books: TRPL 13.2
std: std::iter
Crates: itertools, rayon

Type inference

The compiler infers types within a function body from how values are used, so annotations are rarely needed except on function signatures, which are never inferred.

Books: TRPL 3.2

Turbofish

The ::<> syntax for supplying generic arguments in expression position: "5".parse::<u32>(), iter.collect::<Vec<_>>(). The _ asks the compiler to infer the rest. The name “turbofish” is an informal affectionate name that is evocative of the awkward syntax.

Books: Reference: Paths

Error handling

Result

Recoverable errors are values: Result<T, E> is Ok(T) or Err(E). A Result must be used, or the compiler warns. Libraries tend to define specific error types. Applications tend to use a single catch-all error type for convenience.

Books: TRPL 9.2
std: std::result

The question mark operator

expr? returns early if expr is Err or None, and unwraps the value otherwise. On the way out it calls From::from on the error, which is how one function can propagate several error types into one.

Books: TRPL 9.2, Reference: Operator expressions

The Error trait

The common interface for error types, with a Display message plus an optional underlying source(). thiserror derives it for library errors. anyhow wraps any error with context for applications.

Books: Rust Cookbook: Error handling
std: std::error
Crates: anyhow, thiserror

Panics

Unrecoverable errors like panic!, a failed unwrap, or an out-of-bounds index. By default a panic unwinds the stack, running destructors, and terminates the current thread. Panics are for bugs, not for expected failures.

Books: TRPL 9.1, TRPL 9.3, Nomicon: Unwinding
std: std::panic

Unsafe and FFI

Unsafe Rust

An unsafe block lets you dereference raw pointers, call unsafe functions, and access mutable statics, promising the compiler that you uphold rules it can’t check. When writing unsafe Rust the goal is to wrap small unsafe cores in safe APIs whose safety doesn’t depend on their callers.

Books: TRPL 20.1, Nomicon, Reference: Unsafety

Undefined behavior

Breaking a rule the compiler relies on, such as creating a dangling reference or two live &mut to the same value. UB may not produce a crash. The compiler may assume UB never happens, so UB can produce arbitrary behavior, including a crash. Safe Rust can’t cause it. Unsafe Rust’s primary responsibility is to not cause it. cargo miri test finds much of it in unsafe code.

Books: Reference: Behavior considered undefined, Nomicon: What unsafe can do, Unsafe Code Guidelines

Raw pointers

*const T and *mut T are pointers without lifetimes or borrow rules. Creating one is safe. Dereferencing one is unsafe.

Books: TRPL 20.1
std: std::ptr

FFI

The foreign function interface, calling C from Rust through extern "C" blocks, and exposing Rust to C. bindgen generates Rust declarations from C headers, and cc compiles C and C++ sources in build scripts.

Books: Nomicon: FFI, Reference: External blocks
std: std::ffi
Crates: libc, bindgen, cc

no_std

#![no_std] crates use only core, and optionally alloc, not the OS-dependent parts of std, so they run on bare metal and in other restricted environments.

Books: Embedded Book: no_std, Nomicon: Beneath std
std: core, alloc

Concurrency and async

Threads

OS threads are spawned with thread::spawn, which requires 'static data, or with thread::scope, which may borrow from the enclosing function. The type system prevents data races but not deadlocks, a guarantee often called “fearless concurrency” in Rust.

Books: TRPL 16.1
std: std::thread

Send and Sync

Send types can be moved to another thread. Sync types can be shared between threads by reference. They are auto traits, so most types get them for free. Rc is neither, so it is tied to its thread. RefCell is Send but not Sync. Their thread-safe counterparts are Arc and Mutex.

Books: TRPL 16.4, Nomicon: Send and Sync
std: Send, Sync

Shared state

Data shared between threads lives in an Arc and is mutated through a Mutex or RwLock. A mutex in Rust owns the data it protects, so you can’t read or write the data without holding the lock.

Books: TRPL 16.3, Nomicon: Poisoning
std: std::sync

Atomics

Integer and pointer types updated with single hardware instructions, the building blocks of lock-free code. Each operation takes a memory Ordering. SeqCst is the safe default. Relaxed is for counters. Atomics are tricky to use soundly and hard to debug. Be careful!

Books: Nomicon: Atomics, Reference: Memory model
std: std::sync::atomic

Channels

Message passing between threads, senders on one side, a receiver on the other. std::sync::mpsc covers the basics. crossbeam and tokio have more capable channels.

Books: TRPL 16.2
std: std::sync::mpsc
Crates: crossbeam, tokio

Data parallelism

Splitting one computation over many cores. rayon turns iter() into par_iter() and handles the threads and work splitting.

Books: Rust Cookbook: Concurrency
Crates: rayon

Async and await

async fn returns a Future, a value that makes progress when polled, and .await suspends until another future is done. Futures do nothing until awaited or spawned, and std provides no executor to run them. tokio provides the most common executor.

Books: TRPL 17, Reference: Await expressions
std: std::future, std::task
Crates: futures

Async runtimes

The library that polls futures, schedules tasks, and provides async I/O and timers. tokio is the de facto standard, and most async crates assume it.

Books: TRPL 17.6
Crates: tokio

Pinning

Pin<P> guarantees a value will not move in memory again, which async code needs because futures can hold references into themselves. Most code meets pinning only through Box::pin and the pin! macro.

Books: TRPL 17.5
std: std::pin, Unpin

Code organization

Crates and packages

A crate is the unit of compilation, a library or a binary. A package is defined by a Cargo.toml (manifest) that builds one or more crates. Crates are published to crates.io and documented on docs.rs.

Books: TRPL 7.1, Cargo Book: Manifest, Reference: Crates and source files

Modules and visibility

Modules, declared with mod, organize code within a crate and are the primary boundary of visibility and unsafety in Rust. Items are private to their module unless marked pub, or pub(crate) for crate-wide visibility. use brings paths into scope.

Books: TRPL 7.2, Reference: Visibility and privacy

Preludes

A set of names imported into every module automatically. The standard prelude, chosen by edition, is why Option, Vec, String, and traits like Clone and Iterator need no use. Many crates offer their own prelude to glob-import with use cratename::prelude::*.

Books: Reference: Preludes
std: std::prelude
Crates: rustmax::prelude

Workspaces

Multiple packages sharing one Cargo.lock and target directory, with dependency versions they can declare once and share.

Books: TRPL 14.3, Cargo Book: Workspaces

Features

Cargo features turn optional code and dependencies on and off. Features are unified across the dependency graph, so they must be additive. Enabling a feature should never remove functionality.

Books: Cargo Book: Features

Conditional compilation

#[cfg(...)] includes code only for some targets, features, or test builds, and cfg! tests the same conditions as a boolean. The cfg_if macro chains them like if/else.

Books: Reference: Conditional compilation
Crates: cfg_if

Attributes

Metadata on items, #[derive(Debug)], #[test], #[inline], or on a whole crate, #![no_std]. #[derive] generates trait implementations, and is the most common way to use procedural macros.

Books: Reference: Attributes, Reference: Derive, TRPL Appendix C

Declarative macros

Macros defined with macro_rules! that match token patterns and expand to code. They can do things functions can’t: take a variable number of arguments, or declare items.

Books: TRPL 20.5, Reference: Macros by example

Procedural macros

Macros written as Rust functions over token streams, compiled into their own crate: derive macros, attribute macros, and function-like macros. Nearly all are built from syn, quote, and proc-macro2.

Books: TRPL 20.5, Reference: Procedural macros
Crates: syn, quote, proc_macro2

Build scripts

A build.rs compiled and run before the package itself, to compile C code, generate Rust source, or probe the system. Its output goes to OUT_DIR, and it talks to Cargo by printing cargo:: directives.

Books: Cargo Book: Build scripts
Crates: cc, bindgen

Editions

Opt-in language revisions, 2015, 2018, 2021, and 2024, selected per crate in Cargo.toml. Crates of different editions link together freely, and cargo fix --edition does most of a migration.

Books: Edition Guide

Semantic versioning

Cargo treats version numbers as semver. Before 1.0, a minor bump such as 0.7 to 0.8 is a breaking change, which is why so much of the ecosystem is versioned 0.x.

Books: Cargo Book: SemVer compatibility, Cargo Book: Specifying dependencies
Crates: semver

Idioms and patterns

Newtype

A single-field tuple struct around another type, struct Meters(f64). It gives a value a distinct type at no runtime cost, hides an implementation, and gets around the orphan rule.

Books: TRPL 20.2, API Guidelines: Newtypes
Crates: derive_more

Builder

Constructing a complex value step by step through chained method calls, Command::new("ls").arg("-l").spawn(). This prominent pattern mostly exists because Rust has no named or default arguments.

Books: API Guidelines: Builders
std: std::process

Typestate

Encoding the state of an object in its type, so operations invalid in the current state don’t compile. A method that consumes self and returns a different type moves the object to its next state. This is a lightweight form of typestate analysis.

Books: Embedded Book: Typestate programming

Extension trait

A trait defined only to add methods to a type from another crate, working around the orphan rule. Conventionally named with an Ext suffix, like FutureExt. The extension_trait macro removes the boilerplate.

Books: RFC 445
Crates: extension_trait, futures, itertools

Sealed traits

A public trait that downstream crates can’t implement, because it has a private supertrait. This lets a library add methods to the trait later without breaking anyone.

Books: API Guidelines: Sealed traits

The entry API

map.entry(key) looks a key up once and returns a handle to insert, modify, or read the slot, avoiding a second lookup and fights with the borrow checker: *counts.entry(word).or_insert(0) += 1.

Books: TRPL 8.3
std: Entry

Lazy initialization

Global values computed on first use](https://en.wikipedia.org/wiki/Lazy_initialization). Used when statics can’t be computed at compile time. Typically created with LazyLock and OnceLock.

std: LazyLock, OnceLock

Internals

Monomorphization

Generic code is compiled into a separate copy for each set of type arguments, so it runs as fast as hand-written code at the cost of compile time and binary size. Trait objects are the alternative.

Books: rustc dev guide: Monomorphization

Zero-cost abstractions

The principle, inherited from C++, that abstractions like iterators, closures, and generics cost nothing at runtime compared to writing the code by hand.

Books: TRPL 13.4

The borrow checker

The compiler pass that enforces ownership and borrowing rules. Since “non-lexical lifetimes” it reasons about where references are actually used, not just their lexical scope. “Fighting the borrow checker” is a common experience for new Rust programmers. For experienced Rust programmers it is an indication to restructure.

Books: Nomicon: Limits of lifetimes, rustc dev guide: Borrow checking, RFC 2094

Variance

Whether a generic type with a longer lifetime may be used where a shorter one is expected. &'a T is covariant in T, so it may. &'a mut T is invariant in T, so it may not. It surfaces mostly as confusing lifetime errors in generic code.

Books: Nomicon: Subtyping and variance, Reference: Subtyping and variance

Specialization

A long-unstable feature allowing overlapping trait implementations where the more specific one wins. It is not available on stable Rust, which is why some generic code can’t take fast paths for particular types. The standard library gets to use it to optimize its own types.

Books: RFC 1210