Glossary
162 terms from Rust in Practice, in plain words, each with the chapter that teaches it.
#
- -p (package flag)
- A Cargo option that picks which workspace member a command applies to, using the package name with its hyphens, as in `cargo run -p price-tag`. `--workspace` takes every member.
- [workspace.dependencies]
- A root `Cargo.toml` table listing dependency versions once. Members use them with `.workspace = true`.
A
- ABI (application binary interface)
- The rules for where a compiled function's arguments go and how its result comes back. `extern "C"` makes Rust follow C's ABI so the two languages can call each other.
- allocation
- Asking the system for a piece of memory, as every new `String` does. Many allocations in a hot loop make code slow, which is why code that borrows `&str` instead of copying into new `String`s runs faster.
- API (application programming interface)
- What a crate or service offers to others. In a crate, the `pub` items are its API; in the web service, it's the URLs and JSON that clients can use.
- API token
- A secret key that lets cargo publish crates to crates.io as you. It is shown only once, and you should revoke it if it leaks.
- argument
- A value a command-line program receives by position, such as `HE-5` in `kc price HE-5 --qty 3`.
- atomic type
- A number type, like `AtomicU32`, that several threads can change safely without a lock. It's the safe alternative to a mutable global.
- attribute
- A `#[...]` note attached to an item that changes how the compiler or a library treats it, such as `#[serde(rename_all = "camelCase")]`.
B
- benchmark
- A measurement that runs code many times and reports how long one run takes, with statistics. In Rust the `criterion` crate is the usual tool, for example to compare a slow and a fast version of the same function.
- binary crate
- A crate with a `main` function that builds into a program you can run, like `price-tag`.
- black_box
- A function that hides a value from the optimizer so it can't skip work whose result looks unused. It keeps benchmarks honest.
- breaking change
- A change to a library that can stop users' code from compiling, such as removing or renaming a `pub` function. It requires a new major version, or a new minor version before 1.0.
- build dependency
- A crate used only by `build.rs`, added with `cargo add --build`. The `cc` crate is one.
- build script
- A file named `build.rs` next to `Cargo.toml` that Cargo compiles and runs before building your package. It can prepare things such as compiled C code, often using the `cc` crate.
C
- camelCase
- A naming style where words are joined and each later word is capitalized, like `orderId`. JSON from Bloom Café uses it.
- cargo add
- A command that adds a dependency to a `Cargo.toml`. `-p` picks the package, `--path` points at a local crate, and `--features` turns on a crate's optional parts.
- cargo bench
- Builds in release mode and runs the benchmarks in `benches/`, reporting times and changes since the last run.
- cargo doc
- Builds the HTML documentation from your doc comments. `--open` shows it in the browser, as docs.rs will.
- Cargo feature
- An optional part of a crate that you turn on when adding it, such as `cargo add clap --features derive`. With several crates, a feature is written `crate/feature`.
- cargo flamegraph
- A tool, installed with `cargo install flamegraph`, that profiles a program and writes a `flamegraph.svg`.
- cargo login
- Saves your crates.io API token in `~/.cargo/credentials.toml` so you can publish.
- cargo package
- Packs a crate into a `.crate` file. With `--list` it shows which files would be uploaded.
- cargo publish
- Uploads a crate to crates.io. With `--dry-run` it does every check and build but stops before the upload.
- cargo yank
- Marks a published version so cargo won't choose it for new users. `--undo` reverses it.
- Cargo.lock
- The file where Cargo records the exact version of every dependency. A workspace has one at its root, so all members share versions.
- cdylib
- A crate type that builds a library for another language to load. For wasm it produces the `.wasm` file, and for PyO3 a Python module.
- clap
- The crate that reads and checks command-line arguments, converts them to Rust types and writes `--help` text for you.
- CLI (command-line interface)
- A way of using a program by typing words after its name, like Kettle & Crane's `kc` tool.
- codegen-units
- A release-profile setting. Setting it to 1 compiles the crate as one unit, giving slower builds but sometimes faster code.
- column
- One field of a database table, such as `price_cents`, shared by all its rows.
- commit
- Makes everything done in a transaction permanent. Without it, dropping the transaction rolls the changes back.
- connection pool
- A set of open database connections that are lent to queries, so many tasks can query at once. sqlx's `SqlitePool` is one.
- CORS (cross-origin resource sharing)
- A browser security rule about which pages may load resources from other places. A page opened straight from disk is blocked by it from loading wasm modules, so you serve the folder instead.
- crate
- What the Rust compiler builds in one go: either a binary (a program) or a library (code for others).
- crate metadata
- The `[package]` fields crates.io needs: `description` and `license` are required, while `repository`, `readme`, `keywords` (at most five) and `categories` help people find and trust the crate.
- crates.io
- The public registry of Rust crates that `cargo add` downloads from and `cargo publish` uploads to.
- criterion
- The usual crate for benchmarking Rust code. It runs code many times, reports a range of times and compares with the previous run.
- CString and CStr
- Rust types for C strings: `CString` owns text with a NUL added to hand to C, and `CStr` wraps a C string you got back so you can read it as text.
- CSV (comma-separated values)
- A text format for tables: one row per line, with a header line naming the columns. Jo keeps `products.csv` in it.
- curl
- A command-line program for making HTTP requests, used to try out web services from a terminal. Common options include `-s` (hide progress), `-H` (send a header), `-d` (send a body as a POST), `-i` (show response headers), `-o` (write output to a file) and `-w` (print extra details such as the status code).
D
- dangling pointer
- A pointer to memory that has already been freed, for example after the `Vec` it pointed into was dropped. Reading through it is undefined behavior.
- database
- A store for data that survives when the program stops and can find it quickly.
- debug build
- The default `cargo run` build: quick to compile, full of checks and not optimized. Never time it.
- default (serde attribute)
- A serde attribute that fills a missing field with its type's default, such as `false` or `0`, or with the result of a function you name.
- DefaultBodyLimit
- Axum's cap on request body size, 2 MB by default, so huge uploads are refused with 413. A layer such as `DefaultBodyLimit::max(10_000_000)` raises it.
- deny_unknown_fields
- A serde attribute that makes deserializing fail if the input has fields the struct doesn't know, instead of ignoring them.
- dereference
- Reading or writing the value a pointer points to, using `*`. For a raw pointer this needs `unsafe`.
- doc comment
- A `///` comment documents the item after it and a `//!` comment documents the crate. Tools turn them into `--help` text (clap) or into the pages on docs.rs.
- doc test
- A code example inside a `///` comment, usually under `# Examples`, that `cargo test` compiles and runs to keep docs correct.
- docs.rs
- The site that automatically builds and hosts the documentation for every crate published on crates.io.
E
- edition
- A named version of the Rust language, set in `Cargo.toml`. Edition 2024 needs Rust 1.85 or newer.
- enumerate()
- An iterator adapter that pairs each item with its position starting at 0. The receipt parser uses it to get line numbers.
- environment variable
- A setting passed to a program from the shell, such as `RUST_LOG=debug cargo run`.
- exit code
- The number a program gives the shell when it ends: 0 means success and anything else means failure. `echo $?` shows it.
- extern "C"
- Tells Rust to use C's calling rules. An `unsafe extern "C"` block declares C functions that Rust can call, each call needing `unsafe`.
- externally tagged
- Serde's default enum format, where the variant name wraps the data, as in `{"Courier":{"zip":"97214"}}`.
F
- FFI (foreign function interface)
- The mechanism that lets code in one language call code written in another, like Rust calling Alex's C functions.
- flag
- A command-line name with no value, such as `--help` or `--verbose`. In clap a `bool` field becomes a flag.
- flame graph
- A picture of profiler samples where each box is a function and its width is its share of the time. The widest boxes show where to optimize.
- foreign key (REFERENCES)
- A SQL column that must match an id in another table. In `items`, each `receipt_id` must be the id of a row in `receipts`.
- FromRow
- A derive from sqlx that lets `query_as` fill a struct from a database row, matching column names to field names.
G
- GET and POST
- HTTP methods saying what a request wants: GET reads data, such as a product, and POST sends data to be stored, such as an order.
- glue code
- The JavaScript file wasm-bindgen writes next to the `.wasm` file so a page can call Rust functions with strings and objects, not just numbers.
- graceful shutdown
- Stopping a server by refusing new connections while letting requests already running finish.
H
- handler
- An async function that Axum calls to answer requests on a route, such as `get_product`.
- Host addresses (127.0.0.1, 0.0.0.0)
- 127.0.0.1 (localhost) always means 'this same computer', so a service listening on it can only be reached from the machine it runs on, which suits local development. 0.0.0.0 means 'listen on every network interface', so other machines can reach the service too.
- hot loop
- Code that runs most often in a program, where small costs such as allocations add up.
- HTTP header
- A named piece of extra information sent with an HTTP request or response, such as `Content-Type: application/json`. curl's `-H` adds one.
- HTTP status codes
- The number in a response that tells the client what happened: 201 Created (something new was stored), 404 Not Found, 408 Request Timeout (took too long), 409 Conflict (such as not enough stock), 413 Payload Too Large (body over the limit), 422 Unprocessable Entity (well formed but unacceptable content) and 500 Internal Server Error.
I
- integer overflow
- A number growing past what its type can hold, such as multiplying `u32` cents above about $66,000 by a tax rate. Doing the middle step in a wider type like `u64` avoids it, and `checked_mul` returns `None` instead of overflowing.
- internally tagged
- A serde enum format, chosen with `tag = "type"`, where the variant name goes in a `"type"` field beside the data.
- IntoResponse
- An Axum trait that turns a value into an HTTP response. Implementing it for `AppError` lets handlers return errors as a status and JSON.
J
- JsError
- A Rust error type that wasm-bindgen turns into a JavaScript `Error`. Returning `Err(JsError)` makes JavaScript throw, and `try`/`catch` can catch it.
- JSON (JavaScript Object Notation)
- A text format for data made of objects in braces, lists in brackets, strings, numbers and booleans. Web services, like Kettle & Crane's API, use it.
L
- layer
- Tower's form of middleware. `.layer(...)` wraps every route added before it, for example with logging or a timeout.
- library crate
- A crate with no `main` that holds code for other crates to use, starting from `src/lib.rs`, like `kc-money`.
- log level
- How serious a log message is: `error`, `warn`, `info`, `debug` or `trace`, most serious first. A filter decides which levels are shown.
- lto (link-time optimization)
- A release-profile setting that lets the compiler optimize across crates when linking, usually giving faster, smaller code and slower builds.
M
- match guard
- An `if` after a `match` pattern. The arm matches only if the pattern fits and the condition is also true.
- maturin
- The tool that builds a Rust crate into a Python module. `maturin develop` installs it into the active virtual environment.
- middleware
- Code that wraps every handler of a web service, such as logging requests or limiting how long they take.
- migration
- A numbered SQL file that changes the database's structure, such as creating a table. sqlx applies each one once, in order, and you never edit one that has run.
- Miri
- A tool run with `cargo miri test` that finds many kinds of undefined behavior in unsafe code while tests run.
- Mutex
- A lock letting one thread or task at a time use some data. Never hold the standard Mutex guard across an `.await`; use Tokio's Mutex, whose `lock()` is awaited. `RwLock` allows many readers.
N
- NUL
- The zero byte that ends every C string. Rust strings have no such byte, so `CString::new` adds one and refuses text that already contains one.
- null pointer
- A pointer whose address is 0, pointing at nothing. Reading through it is undefined behavior.
O
P
- package
- A folder with a `Cargo.toml`, holding at most one library crate and any number of binaries.
- panic = "abort"
- A release-profile setting that stops the program immediately on a panic instead of unwinding and cleaning up. It makes the program smaller.
- path dependency
- A dependency on a crate in a folder on your disk rather than on crates.io, as `price-tag` has on `kc-money`.
- perf
- A Linux profiling tool that `cargo flamegraph` uses to sample a running program.
- pipe
- The shell's `|`, which sends one command's output to the next command's input, as in `cat receipt.txt | kc receipt -`.
- placeholder
- A `?` in a SQL statement that `.bind(value)` fills in, so the value is always treated as data and never as SQL.
- port
- A number from 0 to 65,535 that picks which program on a computer receives network traffic. The services here listen on port 3000.
- primary key
- A column whose value must differ in every row, such as `sku` in `products`. SQLite numbers an `INTEGER PRIMARY KEY` itself.
- profiler
- A tool that shows where a program spends its time.
- PyO3
- A crate for writing Python functions and modules in Rust.
- pyproject.toml
- A file next to `Cargo.toml` that tells Python's tools how to build the package; here it names maturin as the build backend.
- PyResult
- PyO3's `Result` type whose error becomes a Python exception. `PyValueError::new_err` makes a `ValueError`.
Q
- query! macros
- sqlx macros that check your SQL against a real database at compile time. They need `DATABASE_URL` and `sqlx-cli`.
R
- raw pointer
- An address with no borrow rules attached, written `*const u32` or `*mut u32`. Making one is safe, but reading through it needs `unsafe`.
- rayon
- A crate whose `par_iter` spreads iterator work across every CPU core. It is a simple way to speed up CPU-heavy loops over collections.
- release build
- A build made with `cargo run --release` or `cargo build --release`: slower to compile but optimized, written to `target/release/`.
- release profile
- The `[profile.release]` section of `Cargo.toml` that tunes the optimizer, with settings like `lto` and `codegen-units`.
- rename and rename_all
- Serde attributes that map Rust names to different names in the data: `rename_all` changes every field or variant, and `rename` changes one.
- resolver
- The `Cargo.toml` setting that controls how Cargo chooses dependency versions. A workspace root must set it, for example `resolver = "3"` for the newest behavior.
- RETURNING
- A SQL clause that makes an `INSERT` hand back values of the new row, such as its `id`.
- roll back
- Undoing every change made since a transaction began. sqlx does it automatically if the transaction is dropped before `commit`.
- Router and State
- An Axum `Router` maps URLs to handlers, and `.with_state(pool)` shares a value, such as the database pool, with every handler that takes `State(pool): State<SqlitePool>`. Axum clones the state for each request.
- row
- One record in a database table, such as one product.
- rust-version
- A `Cargo.toml` field giving the oldest Rust version that can build the crate. Edition 2024 needs 1.85.
- RUST_LOG
- The environment variable that tracing's `EnvFilter` reads to choose which log levels to show, such as `RUST_LOG=debug`.
- rustup
- The tool that installs and manages Rust. `rustup target add` downloads the standard library for another target.
S
- safe wrapper
- A normal function that checks the rule an unsafe operation needs, then does it, so callers can't misuse it. `last_price` checks for an empty list before calling `price_at`.
- SAFETY comment
- A `// SAFETY:` comment explains why an `unsafe` block's rule holds, and a `# Safety` doc section states the rule an `unsafe fn` needs its callers to keep.
- sampling
- A profiling method that stops the program thousands of times a second and records which function was running.
- semver (semantic versioning)
- A version scheme where PATCH is a bug fix, MINOR adds features and MAJOR breaks things. Before 1.0 the rule shifts one place left.
- serde
- The crate behind Rust's serialization. Deriving `Serialize` and `Deserialize` lets a struct convert to and from JSON, TOML, CSV and more.
- serde_json::Value
- A serde_json type that holds any JSON, so you can read data of unknown shape by indexing, like `v["lines"][0]["sku"]`.
- serialize and deserialize
- To serialize is to turn a value into text you can save or send; to deserialize is to turn such text back into a value.
- service
- In tower, anything that takes a request and returns a future of a response; an Axum `Router` is one, so `oneshot` can test it with a single request and no port.
- SIGTERM
- The polite 'please stop' signal that `kill` and container platforms send to a program, which a server should handle with a graceful shutdown.
- skip_serializing_if
- A serde attribute that leaves a field out of the output when a function says so, such as omitting a `None` note instead of writing `null`.
- slice
- A borrowed view of a run of values, such as all or part of a `Vec<u32>`. A `&Vec<u32>` converts to one automatically.
- snake_case
- A naming style with lowercase words joined by underscores, like `order_id`. Rust fields use it.
- SQL (Structured Query Language)
- The language of statements used to control databases, such as `CREATE TABLE`, `INSERT`, `SELECT`, `UPDATE`, `WHERE`, `ORDER BY` and `GROUP BY`.
- SQL injection
- An attack where outside text pasted into a SQL statement changes what it does. Binding values with placeholders prevents it.
- SQLite
- A database kept in a single file, with no server to run.
- sqlx
- An async Rust crate for using SQLite and other databases, with pools, bound queries, migrations and transactions.
- static mut
- A mutable global variable. Every use needs `unsafe`, so an atomic type or `Mutex` is better.
- stderr
- The output stream for problems, written with `eprintln!`. It shows in the terminal but can be redirected apart from stdout.
- stdin
- Text piped into a program. Many tools read it when the file name is `-`.
- stdout
- The output stream for results, written with `println!`.
- subcommand
- A word that picks which job a tool does, like `price`, `list` or `receipt` in `kc`. In clap each enum variant is one.
T
- table
- In TOML, a `[name]` header that starts a group of keys. In a database, a grid of data made of rows and columns, such as `products`.
- target
- A kind of machine Rust can build for. Rustup installs only your computer's target, so you add others, like the browser's `wasm32-unknown-unknown`.
- TimeoutLayer
- A tower-http layer that answers with a chosen status, such as 408, when a handler takes too long.
- tokio::select!
- A macro that runs several futures at once, takes the first to finish and drops the rest.
- tokio::time::timeout
- Wraps a future with a time limit, returning `Ok(value)` if it finishes in time and `Err` otherwise, dropping the future.
- TOML
- The settings format used by `Cargo.toml`, with `key = value` lines and `[name]` headers that start tables. serde reads it with `toml::from_str`.
- tower
- The library Axum is built on, where middleware is a layer and a router is a service. `tower-http` supplies ready-made layers.
- TraceLayer
- A tower-http layer that logs each request at the debug level.
- tracing
- The logging crate most Rust services use. Macros like `info!` record leveled events with fields, and `tracing-subscriber` prints them.
- transaction
- A group of database statements where all take effect or none do. Start one with `pool.begin()` and finish with `commit`.
- trusted publishing
- Publishing crates from a CI system without storing a long-lived API token. The registry instead trusts short-lived credentials proven by the CI service.
U
- undefined behavior
- What happens when unsafe code breaks a rule the compiler relies on: the program may crash, give wrong answers or seem fine until it doesn't.
- union
- A C-style type whose fields share the same memory. Reading a union's field is one of the five things only `unsafe` allows.
- unsafe
- A keyword marking code whose rules the programmer has checked because the compiler can't. It unlocks five extra operations but keeps ownership and borrow checks.
- unsafe function
- A function with a rule its caller must keep that the compiler can't check, such as `get_unchecked` needing an index in range. Callers need an `unsafe` block.
V
- ValueEnum
- A clap derive for an enum whose variants become the fixed words an option accepts, such as `--format text` or `json`.
- Vec::with_capacity
- Creates a `Vec` with room for a known number of items, so it allocates once instead of growing step by step.
- virtual environment
- A folder of Python packages for one project. You create it with `python3 -m venv` and turn it on before installing maturin.
W
- WASI
- The WebAssembly System Interface, a standard that lets wasm programs run outside the browser. Runtimes such as `wasmtime` run them.
- wasm-bindgen
- The crate that writes the glue between Rust and JavaScript so functions can pass strings and objects. `#[wasm_bindgen]` exports a function.
- wasm-opt
- A size optimizer for wasm files that wasm-pack downloads and runs for you.
- wasm-pack
- The tool that builds a Rust crate to wasm and runs wasm-bindgen, producing a `pkg/` folder a web page can load.
- wasm32-unknown-unknown
- The Rust target for WebAssembly in the browser: 32-bit wasm with no operating system. Add it with `rustup target add`.
- WebAssembly (wasm)
- A compact program format that browsers can run at nearly native speed. Rust code, like the price calculator, compiles to it.
- workspace
- A set of packages built together from one root `Cargo.toml`, sharing one `Cargo.lock` and one `target/` folder.
Y
- yank
- To retire a published version so cargo won't pick it for new users. Projects already using it keep working, and nothing is deleted.