137 terms across 10 categories
? unwraps Ok or Some, or returns early on Err or None. In a Result function it also converts the error type with From.
cfg is compile-time conditional compilation. #[cfg(unix)] keeps an item on Unix and strips it elsewhere, so the other branch is not type-checked as live code.
if let runs a block when a value matches one pattern. Use it when you care about a single variant and are willing to ignore the rest.
impl Trait means 'some concrete type that implements this trait' without naming the type. In arguments it is a generic. In return position it is an opaque type.
An impl block attaches functions to a type. impl Session holds inherent methods. impl Trait for Session is the type's implementation of a trait.
IntoIterator converts a value into an iterator. for uses it, and so does anything that takes impl IntoIterator, which is why a function can accept both a Vec and a slice.
Rust has loop, while, while let, and for. for walks an iterator. There is no C-style three-clause for and no foreach keyword.
match chooses a branch by pattern and demands that every possibility is covered. It is the usual way to open an enum and the compiler's exhaustiveness check.
Option is Some(T) or None. It is Rust's replacement for null: a value that might be missing, with the compiler requiring you to say what happens when it is.
Result is Ok(T) or Err(E). It is the standard return type for a computation that can fail, and the type ? knows how to unwrap.
thiserror derives structured error enums for libraries. anyhow provides a boxed, context-carrying error type for applications. They solve different problems and often appear in the same workspace.
unsafe is a keyword that opts a block, function, or trait impl out of some of Rust's guarantees. You become responsible for the invariants the compiler stopped checking.
while let repeats a block as long as a pattern matches. It is the loop form of if let, and it is how you drain iterators and channels without a manual match.
An associated function lives on a type but has no self receiver. Session::new and String::from are the usual examples; they replace constructors and static methods.
An associated type is a type placeholder a trait implementor fills in once, such as Iterator::Item. Callers name it as T::Item instead of adding another generic parameter.
Cargo is Rust's official build tool and package manager. It creates projects, resolves and downloads dependencies, compiles them in the right order, and runs your tests and binaries.
A closure is an anonymous function that can capture bindings from its scope. You write |x| x + 1 and pass it to iterators, threads, and APIs that need a callback.
Compound types group values: tuples, arrays, slices, structs, and enums. They have a known layout at compile time and are the way Rust builds larger values out of scalars.
Control flow in Rust is expression-oriented: if, match, and loop produce values. There is no truthiness; conditions are bool and nothing else.
A crate is the unit Rust compiles at once, either a library or a binary. Modules are the named tree of namespaces inside a crate that organise its items and control what is visible where.
macro_rules! defines a declarative macro by matching token patterns and expanding a template. It is the tool behind vec! and most small helper macros you will write.
Destructuring pulls the pieces out of a value by describing its shape instead of reaching in field by field. You write a pattern that mirrors the value, and Rust binds a name to each part.
Dyn dispatch is a method call through a vtable: the function pointer is loaded at runtime from the trait object, not baked in at compile time.
An enum is a type with a closed list of variants. Each variant may carry its own data. A value is exactly one variant at a time, and match must cover them all.
Rust splits failures into recoverable Result errors and unrecoverable panics. Libraries return Result. Applications decide where to log, retry, or crash.
FFI is how Rust calls C, and how C calls Rust. You declare extern "C" functions, match layouts with repr(C), and treat every crossing as unsafe.
FnOnce, FnMut, and Fn are the three traits a callable can implement. They describe whether calling the value consumes it, mutates it, or only reads it.
A function is a named piece of code with typed parameters and a typed return value. Rust functions do not nest overloads; each fn name in a module is unique.
A generic item is parameterised by types (and sometimes lifetimes and constants). The compiler monomorphises it: one compiled copy per concrete set of parameters.
An iterator is a value that produces a sequence of items by repeating next(). Adapters such as map and filter are lazy: they do nothing until something consumes the iterator.
A macro generates Rust code at compile time. You call one with !, as in println! or vec!. Macros exist because functions cannot take a variable number of typed arguments or generate impls.
A pattern describes the shape of a value and can bind names to pieces of it. Patterns appear in match, if let, while let, let, and function parameters.
A procedural macro is a compiler plugin written in Rust that turns a token stream into another token stream. Derives, attribute macros, and function-like proc macros are the three kinds.
Scalar types hold a single value: integers, floating-point numbers, booleans, and characters. They are fixed-size, live on the stack, and are copied rather than moved when assigned.
Shadowing is declaring a new variable with let that reuses an existing name. The old binding still exists but is hidden, and the new one may have a completely different type.
A struct is a named collection of typed fields. It is Rust's record type: the layout is fixed at compile time, and field access is value.field.
A trait bound restricts a generic type to implementers of a trait. T: Display means the function or impl is only valid when T can be formatted.
A trait object is dyn Trait: a value whose concrete type is erased and whose methods are called through a vtable. You almost always store it behind a pointer, such as Box.
A trait names a set of methods a type can implement. It is Rust's tool for shared behaviour and for generic bounds, not a class you inherit from.
A tuple struct has a name and positional fields, written struct UserId(u64). It is the usual way to wrap one type so the compiler will not mix it with another.
A unit struct has a name and no fields: struct Logout;. It is a zero-sized type, useful as a marker, a trait implementor, or a signal value.
A path names an item in the module tree, such as crate::config::Settings. A use declaration brings a path into scope under a short name so you can stop writing the long version.
let creates a binding between a name and a value, and that binding is immutable unless you write let mut. Immutability is the default in Rust, not an opt-in discipline.
Visibility decides which code is allowed to name an item. In Rust everything is private to its own module by default, and pub and its variants widen that reach one step at a time.
.await suspends the current async function until a future is ready, then evaluates to that future's output. It may only appear inside async code.
Arc is an atomically reference-counted pointer. Cloning an Arc increments a shared count and gives another owner of the same T. The T drops when the last Arc drops.
mpsc means multi-producer, single-consumer. The standard library channel clones the sender and keeps one receiver. It is the default thread-to-thread queue.
Mutex is exclusive locking. lock blocks until it gets a guard, then you may mutate T. Only one guard exists at a time.
RwLock allows many concurrent readers or one writer. read and write return guards that release the lock when they drop.
Send means a value can move to another thread. Sync means a shared reference can. The compiler implements both automatically unless a field forbids it.
async marks a function that returns a Future. The body does not run until the future is polled, usually by a runtime such as Tokio.
Atomic types such as AtomicUsize offer lock-free reads and writes of a single value. You pick a memory ordering; SeqCst is the conservative default.
A channel moves values from sending threads to a receiving thread. Rust's standard channel is multi-producer, single-consumer (mpsc). The value is moved, not shared.
A data race is two threads accessing the same memory at once, at least one writing, without a synchronisation that orders them. In Rust that is undefined behaviour, and safe code is not supposed to be able to do it.
A Future is a value that may produce an output later. The executor calls poll; the future returns Pending or Ready(value). .await is syntax for that poll loop.
A std mutex or write-lock poisons when a thread panics while holding the guard. Later lock calls return Err, because the inner data may be inconsistent.
std::thread::spawn starts an OS thread that runs a closure. The thread owns the closure's captures, which must be Send, and join waits for it to finish.
Tokio is the most common Rust async runtime. It polls futures, provides async TCP and timers, and spawns tasks onto a pool of worker threads.
'static is the lifetime that lasts for the rest of the program. String literals are &'static str. A spawned thread's captures must be 'static because the thread may outlive the stack that created it.
Clone is an explicit duplication. Copy is an implicit bitwise clone. You derive both for simple value types; you implement Clone only when duplication has a cost or a policy.
Drop runs when a value's owner goes out of scope. The compiler inserts the call; you use it to release files, sockets, and other resources.
Pin promises that the value behind pointer P will not be moved in memory. Async state machines need that promise because they may borrow their own fields.
Rc is a single-threaded reference-counted pointer. clone gives another owner of the same T. The last Rc drops the T. It is not Send.
RefCell moves the borrow rules to runtime. borrow and borrow_mut return guards; a conflicting borrow panics instead of failing to compile.
const T and mut T are raw pointers. They may be null, they do not borrow-check, and dereferencing them is unsafe. They are the FFI and allocator vocabulary.
Borrowing lets you use a value without taking ownership. Shared borrows (&T) can be many. A mutable borrow (&mut T) must be the only borrow.
Interior mutability is mutation through a shared reference. Cell, RefCell, Mutex, RwLock, and atomics all wrap an UnsafeCell and reintroduce a safety story the type system can check.
Lifetime elision is the set of rules that fill in 'a for you in common function signatures. One input reference and an output reference are assumed to share a lifetime.
A lifetime is the span for which a reference is valid. The compiler names it 'a in signatures when a returned or stored reference must not outlive its source.
Assignment in Rust moves by default: the source is invalid. Types that implement Copy are duplicated bitwise instead, and both names stay valid.
A mutable reference &mut T is an exclusive borrow. While it lives, nothing else may read or write that T through another path.
Every value in Rust has one owner. When the owner goes out of scope, the value is dropped. Assignment moves the value unless the type implements Copy.
A reference &T is a non-owning pointer the compiler proves is valid for its lifetime. You create one with &value and dereference with * or autoderef.
Locals and fixed-size values live on the stack. Box, Vec, String, and other owning pointers store their payloads on the heap. Rust chooses the heap when the size is dynamic or the value must outlive the frame.
#[test] marks a function as a unit test. cargo test builds a test harness and runs every such function, failing the run if any panics.
assert_eq! panics if two values are not equal, and the panic message prints both sides with Debug. assert_ne! is the opposite check.
assert! panics if a boolean is false. In tests that failure is a failed test. In application code it is a crash you should reserve for broken invariants.
cargo test compiles your crate in test mode and runs unit tests, integration tests, and doc tests. Filters, -- --nocapture, and --test-threads control what runs and what you see.
#[should_panic] marks a test that is expected to panic. The test fails if the function returns normally. An optional expected substring must appear in the panic message.
A code block in a /// doc comment is compiled and run by cargo test as a documentation test. The snippet that users copy is the snippet that must work.
Integration tests live in tests/ and compile as separate crates that depend on your library like any other client. They can see only what is pub.
A mock stands in for a dependency. In Rust you usually extract a trait, implement it for the real type and for a fake, and genericise (or Box) the caller.
Box is an owned heap allocation of a single T. When the box drops, it drops T and frees the memory. It is the simplest smart pointer.
BTreeMap is an ordered map backed by a B-tree. Lookup is O(log n). Iteration is in key order, and you can query ranges of keys.
BTreeSet is a sorted set of unique values backed by a B-tree. Membership is O(log n), iteration is in Ord order, and range queries are native.
Cow is clone-on-write: either a borrow of B or an owned B::Owned. You clone only when a mutation or an API requires ownership.
HashMap is a hash table from keys to values. Average lookup, insert, and remove are O(1). Keys must implement Eq and Hash.
HashSet is a hash table of unique values. Insert, remove, and membership tests are average O(1). It is a HashMap with a set-shaped API.
OsString is an owned string in the platform's encoding. Use it for command-line arguments and paths that may not be valid UTF-8.
String is an owned, growable UTF-8 buffer. &str is a borrowed slice of UTF-8. Functions that only read text should take &str; functions that must keep text should take String.
Vec is a growable, contiguous array on the heap. It is the default list type in Rust: indexed in O(1), appended in amortised O(1), and iterated in a tight pointer loop.
VecDeque is a double-ended queue backed by a ring buffer. Push and pop at either end are amortised O(1), which is the operation Vec makes expensive at the front.
An array [T; N] is N values of type T stored inline. N is part of the type, so [u8; 4] and [u8; 16] are different types.
A linked list is nodes joined by pointers. Rust's std::collections::LinkedList exists, and for most programs a Vec or VecDeque is the better choice.
A slice &[T] is a borrowed view of a contiguous run of elements. It is a pointer plus a length, and it is the type you want for "read these items" regardless of whether they live in a Vec or an array.
A method in Rust is a function inside an impl block whose first parameter is self, &self, or &mut self. The method is namespaced on the type; it is not looked up on a class or a prototype chain.
Rust has no inheritance of data or behaviour. You reuse code by putting one struct inside another, and you share behaviour with traits. "Is-a" is not a relationship the language will draw for you.
Drop is Rust's destructor trait. When a value goes out of scope, the compiler inserts a call to Drop::drop and then drops each field. You use it to release sockets, files, and other resources that are not just memory.
A Rust struct is a named bundle of fields, not a class. It holds data; behaviour is added later with impl. There is no hidden object header and no inheritance tree attached to the type.
A trait is Rust's interface: a named set of method signatures that a type can implement. Polymorphism is "any type that implements this trait", not "any subclass of this class".
Rust encapsulates by module visibility, not by class boundaries. Fields and items are private to their module unless marked pub. Privacy is how you keep a struct's invariants from being broken by outsiders.
map transforms each item, filter keeps some items, and fold collapses the sequence to one value. Together they are the core iterator pipeline.
Breadth-first search walks a graph level by level using a queue. On an unweighted graph, the first time you reach a node is a shortest path in number of edges.
BinaryHeap is a max-heap priority queue. push and pop are O(log n). The greatest Ord value comes out first.
Binary search finds a target in a sorted slice in O(log n) comparisons. Rust exposes it as slice::binary_search and the _by / _by_key variants.
Depth-first search walks a graph by going as deep as possible before backtracking. Implement it with the call stack or with an explicit Vec stack.
Dynamic programming solves a problem by combining answers to overlapping subproblems, storing each answer once. In Rust that store is usually a Vec, a HashMap, or an #[cached]-shaped memo table.
A greedy algorithm makes the locally best choice and never revisits it. It is fast when you can prove that local choice is safe, and wrong when you cannot.
Iterator adapters are methods that wrap an iterator and change what it yields: map, filter, take, flat_map, enumerate. They are lazy and usually fuse into one pass.
A prefix-sum array stores at i the sum of the first i elements so any range sum becomes two lookups. You pay O(n) to build and O(1) per query.
A recursive function calls itself with a smaller input until a base case. In Rust each call is a stack frame; a deep recursion will overflow the stack even if the heap is empty.
A sliding window maintains a contiguous subarray (or substring) that moves across the input. You add on the right and drop on the left instead of recomputing each span from scratch.
slice::sort is a stable, O(n log n) sort. sort_unstable is usually faster and may reorder equal elements. Both need T: Ord, or you pass a comparison with sort_by.
Space complexity is how extra memory grows with n. In Rust that includes heap allocations, recursion depth, and the hidden buffers inside collect and clone.
Time complexity describes how the work of an algorithm grows with the input size n. Rust does not change the math: a nested loop over n elements is still O(n²), even when the types are fancy.
Two pointers is a technique that walks a slice with two indices — often from both ends, or a slow and a fast pointer — to get an O(n) pass instead of a nested O(n²) scan.
Actix Web is a high-performance HTTP framework on the Actix actor runtime. You register handlers on an App, extract request data, and return types that become responses.
Axum is a Tokio-first web framework built on hyper and Tower. You declare a Router, attach handlers, and extract typed inputs from the request.
CORS is a browser rule that blocks a page on origin A from reading a response from origin B unless B opts in with headers. Servers set those headers; browsers enforce them.
An extractor is a typed argument to a handler that is built from the request: path params, query strings, JSON bodies, headers, and shared state.
HTTP is the request/response protocol of the web. In Rust you speak it with a client crate (reqwest) or a server crate (Axum, Actix) sitting on Tokio and a type that maps headers, method, path, and body.
Serde is Rust's serialisation framework. #[derive(Serialize, Deserialize)] on a struct, plus serde_json, turns JSON into typed values and back.
Tower is a library of middleware traits (Service, Layer) for request/response services. Axum and many hyper clients compose timeouts, retries, and tracing as Tower layers.
A builder is a type that collects optional fields and then builds the real value. In Rust it replaces default arguments and telescoping constructors.
An extension trait adds methods to a type you do not own. You declare the trait, implement it for the foreign type, and callers import the trait to see the methods.
A facade is a narrow type or module that hides a noisy subsystem. Callers talk to one struct; the facade talks to the parser, the HTTP client, and the cache.
A newtype is a tuple struct around an existing type, struct UserId(u64), so the compiler will not accept a raw u64 or a SessionId in its place.
RAII ties a resource to a value. The constructor acquires; Drop releases. A drop guard is a small type whose only job is that destructor, even if you forget every other path.
The strategy pattern is a family of interchangeable algorithms. In Rust each strategy is a type that implements a trait, and the context is generic over that trait or stores Box.
Typestate encodes an object's stage of life in a generic parameter so illegal calls do not compile. A Connection has no read method.
A visitor walks a closed structure and runs per-node behaviour. In Rust the structure is usually an enum, and the visitor is a match or a trait with one method per variant.
A connection pool keeps a set of live database connections and lends them out. Creating a TCP+TLS+auth session per request is too slow and will exhaust the database.
Diesel is a mostly-sync ORM and query builder. A compiled schema module plus a Rust DSL produce SQL, and the compiler checks that columns and types match.
SeaORM is an async ORM built on SQLx. You define entities, walk relations, and still drop to SQL when the query builder runs out.
SQL injection is attacker-controlled text becoming part of a query's syntax. The fix is bind parameters, never string concatenation of user input into SQL.
SQLx is an async SQL crate that talks to Postgres, MySQL, and SQLite without an ORM. Queries are strings (or macros that check them against a live database at compile time).
A transaction is a group of statements that commit together or roll back together. In Rust you begin a transaction on a connection, run queries on that handle, and commit — or drop the handle and roll back.