Skip to content

Rust Beyond the Basics

Glossary

114 terms from Rust Beyond the Basics, in plain words, each with the chapter that teaches it.

#

#[test]
An attribute marking a function as a test that fails if it panics. `#[cfg(test)]` compiles a module only when testing, and `#[should_panic]` makes a test pass only if the code panics.
'static
A lifetime meaning a reference is valid for the whole run of the program. Quoted text like "HE-5" is always `&'static str` because it is stored inside the program itself.
.await
Runs a future to completion and gives its result. It can be used only inside an `async fn` or async block.

A

adapter
An iterator method such as `map` or `filter` that turns one iterator into another. Adapters are lazy and do nothing until a consumer asks for values.
anyhow
A crate for error handling in applications. Its single `anyhow::Error` type holds any error, and you can add context messages like "reading prices.txt" to explain what failed.
API (Application Programming Interface)
A set of requests that a program answers for other programs. Kettle & Crane's order service is an API that cafés' systems call.
Arc (atomically reference counted)
The thread-safe version of `Rc`: it counts owners with a count that can safely change from several threads. `Arc<Mutex<T>>` is the usual way to share changeable data across threads or tasks.
assert!, assert_eq!, assert_ne!
Macros that check a result in a test and panic if the check fails, which makes the test fail. `assert_eq!` checks two values are equal, `assert_ne!` that they differ, and `assert!` that a condition is true.
associated type
A type that a trait leaves for each implementation to choose, such as `Item` in `Iterator`. It is referred to as `Self::Item`.
async block
A piece of code written `async { ... }` that makes a future. `async move` takes ownership of the variables it uses, like a `move` closure, which `tokio::spawn` needs.
async fn
A function that does not run when called but returns a future. The work happens only when the future is awaited, letting one thread handle many waiting jobs.
Axum
A web framework crate that does the HTTP work so you write only what each request should do. It runs on Tokio.

B

bail!
An anyhow macro that returns early with an error built from a message, formatted like `format!`. `anyhow!` makes the same error without returning it.
borrow checker
The part of the Rust compiler that makes sure every reference is used only while the value it points to is still alive.
Box
A smart pointer that puts one value on the heap; the box itself is just an address. It lets a Vec own mixed types (`Vec<Box<dyn Shippable>>`) and lets a type contain itself.
Box<dyn Error>
A box holding any type that implements the standard `Error` trait. It lets one function return different kinds of errors, but the error is vague.

C

capture
A closure using a variable from the code around it, such as `discount` using `rate`. By default it borrows the variable; `move` makes it take ownership.
cargo add
A Cargo command that adds a crate (library) to your project, optionally with features switched on, as in `cargo add serde --features derive`.
cargo doc --open
Builds the documentation of your own project and opens it in the browser.
cargo run --bin
Runs one of the programs in `src/bin/`, each file being its own program, for example `cargo run --bin ch10_server`.
cargo test
Builds and runs all tests (unit, integration and doc tests). Adding part of a name, as in `cargo test discount`, runs only matching tests.
channel
A one-way pipe between threads: one end sends values and the other receives them. `mpsc::channel()` returns a sender `tx` and a receiver `rx`.
checked_mul
A method that multiplies and returns `Some(answer)`, or `None` if the result is too big for the type. `checked_add` does the same for addition, so the order service can reject huge orders instead of crashing.
client
The program that sends a request, such as a browser, an app or `curl`.
Clone
A trait that gives a type a `.clone()` method to make a copy of a value. Deriving `Clone` requires every field to be cloneable.
closure
A function without a name, written inline like `|x| x * 2`, that can use variables from the code around it.
collect
An iterator consumer that gathers items into a collection such as a `Vec`, `HashMap` or `String`, or into a single `Result`. You usually tell it the target type with an annotation or the turbofish.
concurrency
Several pieces of work being in progress at the same time, like two packing stations at Alex's desk.
const
A value fixed at compile time. The order service's `CATALOG` is a `const` array of SKU and price pairs.
consumer
An iterator method that uses up the iterator and gives a result, such as `collect`, `sum`, `count`, `find` or `any`. Consumers are what make lazy adapters actually run.
Copy
A trait that makes a value be copied instead of moved when assigned. A type can be `Copy` only if every field is `Copy`, so a struct with a `String` cannot.
crate
A Rust library or package that you can add to your project, such as serde or Axum.
curl
A command-line tool for sending web requests. Flags used here: `-i` shows the status line and headers, `-X` sets the method, `-H` adds a header and `-d` gives the body.

D

deadlock
A situation where threads each wait for a lock another holds, so the program hangs forever. Locking in one consistent order avoids it.
default method
A trait method that has a body, so every implementing type gets it for free and may override it. `label` in `Shippable` is one.
Deref
A trait that lets `*` follow a pointer to the value inside and lets method calls reach through it. `Box`, `String`, `Vec` and `Rc` implement it.
derive
An attribute that has the compiler write a trait implementation for you, as in `#[derive(Debug, Clone)]`. It works only if every field has the trait.
Display
The standard trait that controls how `{}` prints a value. You implement its `fmt` method, and you then also get `to_string()`.
doc test
A code example inside a `///` doc comment that `cargo test` also runs, so documentation examples stay correct.
Drop
A trait whose `drop` method runs when a value goes away. Smart pointers use it to free memory; the `drop(value)` function ends a value early.
dyn
The keyword used for a trait object, as in `&dyn Shippable`, meaning some value of any type that implements the trait, with the method found while the program runs.

E

Error trait
The standard trait that error types implement. A custom error needs `Debug`, `Display` and this trait, whose methods all have defaults.
extractor
An Axum handler parameter that pulls something out of the request, such as `Path`, `State` or `Json`.

F

feature
An optional part of a crate that you switch on, as in `cargo add tokio --features full`.
Fn
The three closure traits: `Fn` only reads what it captures and can be called repeatedly, `FnMut` changes captures, and `FnOnce` gives a captured value away so it can run only once.
Formatter
The place text goes when you implement `Display`. The `write!` macro writes into it and returns a `fmt::Result`.
From
A trait for converting one type into another. The `?` operator uses it to convert an error into the function's error type, and thiserror's `#[from]` writes the impl for you.
future
A value representing async work that will finish later. Futures are lazy and do nothing until awaited.

G

generic
Code written once with a type parameter so it works for many types, such as `cheapest` for `u32`, `f64` and `&str`.
guard
The value `lock()` returns on a `Mutex`. You use it like a `&mut` to reach the data inside, and dropping it releases the lock.

H

handler
An `async fn` that answers one kind of request in Axum, such as `list_products`.
HashMap
A collection that stores key-value pairs and looks up a value quickly by its key. In the order service, a `HashMap` keyed by order id finds each stored order.
header
A labeled fact about an HTTP message, such as `Content-Type: application/json`, which tells the server the body is JSON.
heap
The area of memory where values can live beyond a single function's local variables. `Box`, `String` and `Vec` keep their data there and free it when they go out of scope.
HTTP (HyperText Transfer Protocol)
The rules the web runs on: a client sends a request with a method (GET to read, POST to send something new) and a path like `/products`, and the server sends a response.
HTTP status codes
The number in an HTTP response saying how it went: 200 OK, 201 Created, 204 No Content, 400 Bad Request, 404 Not Found, 415 Unsupported Media Type (missing JSON header) and 422 Unprocessable Entity (bad or missing fields).

I

impl Trait
Syntax meaning "any type that implements this trait", as in `fn postage(item: &impl Shippable)` or a returned `impl Fn(u32) -> u32`. It is a shorthand for a generic with a trait bound.
integration test
A test that uses your package from the outside as another program would, placed in a `tests/` folder and seeing only `pub` items.
interior mutability
Changing data through a value that isn't declared `mut`. `RefCell` allows it by checking the borrow rules while the program runs, and `Mutex` allows it through locking.
IntoResponse
Axum's trait for anything a handler can return. Axum calls it to build the HTTP response, and types like `Json`, `StatusCode`, `String` and tuples implement it.
iter, iter_mut, into_iter
The three ways to get an iterator from a `Vec`: lend each item for reading, lend each item to change, or hand over the items themselves and use up the Vec.
Iterator
A value that produces a series of items one at a time through `next()`, which returns `Some(item)` until it returns `None`. Implement the trait for your own type to get every adapter and consumer.

J

JoinHandle
What `thread::spawn` or `tokio::spawn` returns. Its `join` (or awaiting it, for tasks) waits for the work to finish and gives back a `Result` with the return value.
Json (Axum)
An Axum wrapper that sends a value as JSON when returned, and as an extractor reads and deserializes the request body. As an extractor it must be the last parameter.
JSON (JavaScript Object Notation)
A text format for data: `{"sku":"HE-5","qty":3}` is an object with named fields and `[...]` is a list. The `json!` macro builds JSON values in code.

L

lazy
Doing nothing until asked. Iterator adapters and futures run only when something consumes or awaits them.
lifetime
How long a reference is valid. Annotations describe how references relate to each other but never make anything live longer.
lifetime elision
Three rules the compiler uses to fill in lifetimes so you can leave them out, for example in a function with one reference parameter or a method with `&self`.
lifetime parameter
A name starting with an apostrophe, usually `'a`, that links the lifetimes of inputs and output, as in `fn longer_name<'a>(a: &'a str, b: &'a str) -> &'a str`. Structs holding references need one too.

M

map_err
A `Result` method that changes the error inside an `Err` with a closure and leaves an `Ok` alone.
monomorphization
The compiler writing a separate copy of generic code for each type it is used with, so generics cost nothing at run time.
move
A keyword that makes a closure take ownership of the variables it captures. It is needed when the closure outlives them, as with returned closures and threads.
mpsc (multiple producer, single consumer)
The kind of channel in the standard library: many senders but only one receiver. You clone the sender for each thread.
Mutex
A lock that lets only one thread or task at a time reach the value inside. `lock()` waits for its turn and returns a guard; dropping the guard releases the lock.

O

orphan rule
You may implement a trait for a type only if the trait or the type is your own. You can't implement the standard `Display` for the standard `Vec`.
overflow
A number too big for its type. A plain `*` that overflows panics in a debug build and silently wraps to a wrong number in a release build.
overriding
Giving a type its own version of a trait's default method, as `Mug` does with `label`.

P

parallelism
Pieces of work running at the very same instant on different processor cores, as opposed to merely being in progress together.
PartialEq
The standard trait behind `==` and `!=`. Deriving it makes two values equal when all their fields are equal.
PartialOrd
The standard trait behind `<` and `>`. Generic code needs it as a bound, `T: PartialOrd`, to compare values.
Path
An Axum extractor that takes a changing part of the URL path, such as `{sku}` in `/products/{sku}`, and unwraps it with `Path(sku)`.
pointer
A value that holds the address of other data, as a reference does. A smart pointer also owns the data.
poisoning
The state a mutex gets when a thread panics while holding its lock, so later `lock()` calls return `Err`.
port
A numbered door into a computer, such as 3000 where the example servers listen. The servers bind to `127.0.0.1`, which means this computer only.

R

Rc (reference counted)
A smart pointer for shared, read-only ownership on one thread. It counts the owners and drops the value when the count reaches zero.
recursive type
A type that contains itself, such as a bundle holding other bundles. It needs a `Box` since a value can't hold a full copy of itself.
RefCell
A type that checks the borrow rules while the program runs instead of at compile time. `.borrow()` reads and `.borrow_mut()` writes, and it panics if the rules are broken.
request
What a client sends to a server: a method, a path, and sometimes a body.
response
What a server sends back to a client: a status code, headers and usually a JSON body.
Router
Axum's type that maps requests (method and path) to handlers; `.with_state(...)` gives every handler shared data.
runtime
The code that runs asynchronous tasks and drives futures to completion. Rust's standard library doesn't include one, so programs use a crate such as Tokio.

S

Send
Marker traits for thread safety: `Send` means a value can move to another thread, and `Sync` means it can be shared by reference between threads. `Rc` has neither; `Arc` and `Mutex` have both.
serde
The crate that converts Rust values to and from formats like JSON. `Serialize` lets a value be written out and `Deserialize` lets it be built from text; both can be derived.
server
The program that answers requests, such as the Axum order service.
signature
A function's name, parameters and return type, without its body. The borrow checker uses a function's signature, not its body, to decide what a returned reference borrows from.
slice
A borrowed view of part or all of a list, written `&[T]`. A `&Vec<T>` can always be passed where a slice is expected.
smart pointer
A value that owns data and adds an ability, such as `Box`, `Rc`, `String` and `Vec`.
State
Data an Axum router hands to every handler, stored with `.with_state(...)` and read with the `State` extractor, usually an `Arc<Mutex<...>>`.
static dispatch
With `impl Trait` or generics, the compiler knows the exact type and chooses the method while compiling (static). With `dyn Trait`, the program looks up the method while running (dynamic), which lets mixed types share a list.

T

task
A future that the runtime runs on its own, like a lightweight thread, started with `tokio::spawn`. Awaiting its `JoinHandle` gives its result.
thiserror
A crate whose derive writes `Display`, `Error` and `From` for your own error enum from `#[error("...")]` and `#[from]` attributes. It suits libraries.
thread
A separate line of work inside a program, started with `thread::spawn`. `thread::scope` starts threads that are all joined before it returns, so they may borrow local variables.
Tokio
Rust's most used async runtime. `#[tokio::main]` starts it, `tokio::join!` waits for several futures at once, and `tokio::time::sleep` pauses without blocking the thread.
trait
A named set of methods a type promises to have. Code that knows the trait can use any type that implements it, such as `Shippable`.
trait bound
A rule on a type parameter saying what it must implement, like `T: PartialOrd`. Several bounds are joined with `+`.
trait object
A value used through `dyn Trait`, of any type with that trait. It lets different types, like a `CoffeeBag` and a `Mug`, sit in one `Vec`.
turbofish
The `::<Type>` syntax after a function name that tells Rust which type to use, as in `parse::<u32>()` or `collect::<Vec<_>>()`.
type alias
A short name for a type, such as `type AppState = Arc<Mutex<Store>>;`.
type parameter
A stand-in name for a type, usually `T`, declared in angle brackets after a function or struct name. It means "whatever type the caller uses".

U

unit test
A test written next to your code, in a `#[cfg(test)] mod tests`, that can test even private functions.
unwrap
Takes the value out of an `Ok` or `Some` and panics otherwise. `unwrap_err` does the opposite for a `Result`, giving the error inside an `Err`.
usize, u32, u64
Unsigned whole-number types. `usize` is the one Rust uses for sizes and positions, and `u32`/`u64` are 32- and 64-bit versions.

W

where clause
A way to write trait bounds after the parameters and return type, which keeps long signatures readable.
with_context
An anyhow method that wraps an error with what you were doing, such as "reading prices.txt". It takes a closure so the message is built only on error; `.context` takes a ready-made message.