Glossary
158 terms from Rust Basics, in plain words, each with the chapter that teaches it.
#
- #[derive(Debug)]
- An attribute that asks the compiler to write the code that lets your struct print with `{:?}`.
- &&, ||, ! (logical operators)
- Operators that combine true/false conditions: `&&` means both must be true, `||` means at least one must be true, and `!` flips true to false. For example, `(state == "OR" || state == "WA") && bags >= 5` checks for a local order of at least 5 bags.
- :: (path separator)
- Two colons that reach an item that belongs to a type or module, as in `String::from` or `money::format_cents`.
- ? operator
- Placed after something that returns a `Result`, it takes out the value if it is `Ok`, or returns the error to the caller straight away if it is `Err`. It only works in a function that itself returns a `Result` or `Option`.
- _ (wildcard pattern)
- In a `match`, `_` matches anything not covered by earlier arms, so it is put last. In a `for` loop, `_` names a variable you don't need.
A
- Argument
- A value you pass to a function when you call it, such as `1500` in `print_price("Mug", 1500)`. Arguments match the function's parameters by position.
- Arm
- One line of a `match`, made of a pattern, `=>`, the code to run and a comma. The first arm whose pattern fits is the one that runs.
- Array
- A fixed-length group of values that are all the same type, such as `[5500, 7200, 6200]`. Items are reached by index starting at 0.
- as
- A keyword that converts a value on purpose from one number type to another, such as `bags as f64`. Converting a float to an integer drops everything after the point.
- Associated function
- A function inside an `impl` block that has no `self`, so it belongs to the type rather than one instance. You call it with `::`, like `Product::new(...)`.
- async
- A way of writing programs that can wait for slow things, like network requests, without blocking everything else. In Rust it is usually used together with a runtime such as Tokio.
- Attribute
- An instruction to the compiler written as `#[...]` above an item, such as `#[derive(Debug)]` above a struct.
- Axum
- A Rust library for building web APIs. It can be used, for example, to build an order service for Kettle & Crane's shop.
B
- Binary
- A project that builds into a program you can run, which is what `cargo new` makes by default.
- Bit
- A single 0 or 1 in a computer's memory. An integer type's number, such as the 32 in `u32`, is how many bits it uses.
- Block
- Code between braces `{ }`. The last expression in a block, with no semicolon, is the block's value.
- bool
- A type with only two values, `true` and `false`. Comparisons such as `stock < 20` produce a `bool`, and `if` conditions must be one.
- Borrow
- Using a value through a reference without owning it, like holding up an order ticket for the barista to read. The original owner keeps the value and can use it afterwards.
- break
- A keyword that stops a loop immediately and carries on with the code after it.
- Byte
- Eight bits, the unit memory is measured in. A `String`'s `len()` counts bytes, so `é` counts as 2.
C
- CamelCase
- A naming style where each word is capitalized with no underscores, like `OrderLine`. Rust uses it for structs, enums and variants.
- Cargo
- Rust's project tool. It creates projects, runs the compiler, runs your program and fetches crates other people have published.
- cargo add
- A command that adds a crate from crates.io to your project's dependencies, as in `cargo add rand`.
- cargo build
- Compiles your project without running it. Adding `--release` builds a faster, optimized version in `target/release`.
- cargo check
- Checks your code for errors without building the app, which is faster than a full build.
- cargo clippy
- A tool that comes with Rust and checks your code for over 800 common mistakes, suggesting better code.
- cargo doc
- Builds documentation pages for your own project and its dependencies from their doc comments, and `--open` shows them in your browser.
- cargo fmt
- A tool that comes with Rust and lays out your code in the standard style.
- cargo new
- Creates a new project folder with `Cargo.toml` and a small starter program in `src/main.rs`, as in `cargo new kettle`.
- cargo run
- Compiles your project and runs the program in one step. If the compiler finds an error, nothing runs.
- Cargo.lock
- A file Cargo writes that records the exact versions of every crate your project uses, so later builds use the same ones.
- Cargo.toml
- The project's settings file, where Cargo keeps its name, version and list of dependencies.
- cd (change directory)
- A terminal command that moves you into another folder, such as `cd Documents/rust`.
- char
- A type holding one character, written in single quotes like `'L'`. Text of any length uses double quotes instead.
- Clone
- A method that makes a full copy of a value, including its heap data, so each variable owns its own. It costs time and memory for big values.
- collect
- A method that gathers the values an iterator hands out into a collection, such as a `Vec<&str>`. The type annotation tells it which kind of collection to build.
- Collections
- Standard library types that hold many values and keep them on the heap so they can grow and shrink, such as `Vec` and `HashMap`.
- Comment
- Text after `//` that is a note for humans; the compiler ignores it.
- Comparison operators
- Operators that compare two values and give a `bool`: `==` equal, `!=` not equal, `<` less than, `>` greater than, `<=` at most, `>=` at least. One `=` stores a value, so use `==` to compare.
- Compiler
- The program (`rustc`) that reads your code, checks it and turns it into an app your computer can run. Rust's compiler refuses to build code that might mishandle memory and explains why.
- Compiler error
- A message from the compiler saying your code can't be built, so nothing runs. Read it from the top: the first line says what's wrong, the `-->` line says where, and `help:` often suggests the fix.
- Compound assignment operators
- Shortcuts that change a `mut` variable using its old value: `stock -= 2;` means `stock = stock - 2;`, and `+=`, `*=` and `/=` work the same way.
- concurrency
- Doing several things at overlapping times in one program. It lets a program make progress on multiple tasks, such as handling many requests, instead of finishing one before starting the next.
- Condition
- An expression that gives a `bool` and decides what an `if` or `while` does. It must really be a `bool`, not a number.
- Constant
- A name for a value that never changes anywhere in the program, written with `const` outside `main`, in UPPERCASE, with its type, like `const SHIPPING_CENTS: u32 = 1200;`.
- continue
- A keyword that skips the rest of the current loop pass and goes straight to the next iteration.
- Control flow
- The order in which lines of a program run, including skipping, choosing and repeating them.
- Copy
- The ability of simple, fixed-size types like numbers, `bool` and `char` to be copied cheaply instead of moved. After `let b = a;` with an integer, both stay usable.
- Crate
- A package of Rust code that the compiler builds as one unit. Your own project is a crate, and so is the standard library.
- crate:: (path)
- In a path, `crate` means the top of the current crate, which is `main.rs`. `use crate::money;` lets another file reach the `money` module.
- crates.io
- Rust's public registry where people publish crates that you can add to your project for free.
D
- Dangling reference
- A reference that points at a value that has already been dropped. Rust refuses to compile code that would create one.
- Debug format
- A programmer's view of a value, printed with `{:?}` on one line or `{:#?}` spread over several lines. It is meant for checking what's inside, not for customers.
- Dependency
- A crate your project uses, listed under `[dependencies]` in `Cargo.toml`, like `rand`.
- Dereference
- Reaching the value a reference points to by putting `*` in front of it, as in `*cents += 300;`.
- Doc comment
- A comment starting with `///` that describes the item below it. Cargo turns doc comments into documentation.
- docs.rs
- A website with documentation for every crate on crates.io, built from its doc comments, for example docs.rs/rand.
- Drop
- Handing a value's memory back when its owner goes out of scope. Rust does this automatically, exactly once.
E
- E0xxx error codes
- Each Rust compiler error has a code like `E0384`. Running `rustc --explain E0384` prints a longer explanation of that error.
- entry / or_insert
- A `HashMap` pattern that finds a key's value, first inserting a starting value like 0 if the key is new, and returns a mutable reference to it. It is the classic way to count things, as in Jo's sales totals.
- Enum
- A type whose value must be exactly one of a fixed list of choices called variants, like a `Grind` that is `WholeBean`, `Espresso`, `Filter` or `FrenchPress`.
- Exhaustive
- Covering every possible value. A `match` must be exhaustive, or the compiler reports an error until you add the missing arm or a `_` arm.
- expect
- Like `unwrap`, it takes the value out of an `Ok` or `Some`, but if there is none it panics with your own message.
- Expression
- Code that produces a value, like `1650 * 2` or an `if` with an `else`. Adding a semicolon turns it into a statement that throws the value away.
F
- f64
- Rust's usual type for numbers with a decimal point. It is fine for weights and averages but not exact for money.
- Field
- A named value inside a struct, such as `price_cents` in `Product`. You read one with a dot, like `mug.name`.
- Field init shorthand
- When a variable has the same name as a struct field, you can write it once, like `price_cents,` instead of `price_cents: price_cents`.
- Float
- A number with a decimal point, such as an `f64`. Floats can't store most decimal fractions exactly, so `0.1 + 0.2` gives `0.30000000000000004`, which is why money is kept in cents.
- fn
- The keyword that starts a function definition.
- for
- A loop that runs its block once for each value in a sequence such as a range or array.
- format!
- A macro that works like `println!` with the same placeholders but returns a new `String` instead of printing.
- Function
- A named block of code that does one job. You run it by calling its name, and it can take inputs and give back a result.
G
- Garbage collector
- A helper in some other languages that frees unused memory while the program runs. Rust doesn't use one; its ownership rules, checked by the compiler, do the job.
- Generic type
- A type with a slot for another type, such as `Option<u32>` meaning "maybe a `u32`".
- get
- A method on `Vec` and `HashMap` that looks up an item and returns an `Option`, so a missing position or key gives `None` instead of a panic.
H
- HashMap
- A collection of key-value pairs: give it a key like a product name and it returns the stored value, such as a count. It keeps no order and needs `use std::collections::HashMap;`.
- Heap
- Memory for values whose size can change, like a growing `String`; it's like the storeroom out back. The program keeps a small record on the stack pointing to it.
I
- if / else
- `if` runs a block only when its condition is `true`; `else if` tests more conditions in turn and `else` runs when none was true. An `if` with an `else` also produces a value.
- if let
- A shorter form of `match` that runs a block only if a value fits one pattern, such as `if let Some(cents) = price`. It doesn't check the other cases.
- Immutable
- An immutable variable can't be changed after it's set, which is Rust's default; a mutable one, declared with `mut`, can. The default means you know a value from one line of code.
- impl
- A block that holds the methods and associated functions of a struct or enum.
- Index
- A position in square brackets that picks an item out of an array or vector, counting from 0, like `prices[0]`.
- Instance
- One value of a struct type, made by giving every field a value, such as the `mug` that is a `Product`.
- Integer
- A whole number type. `i32` is the default, `u32` can't be negative, and the number is how many bits the type uses.
- Integer division
- With integers, `/` drops the remainder, so `17 / 5` is 3, while `%` gives the remainder, 2. Together they turn cents into dollars and cents.
- Iteration
- One pass through a loop's block.
- Iterator
- Something that hands out values one at a time, like `lines()` and `split()`. Rust has many more iterator methods, which the next book covers.
K
- Key-value pair
- A key, like a product name, stored with the value it looks up, like a stock count. A `HashMap` is made of these pairs.
- Keyword
- A word with a fixed meaning in Rust, such as `let`, `fn` or `if`, that can't be used as a name.
L
- len
- A method that gives how many items an array, `Vec` or `HashMap` holds. On text it gives the length in bytes, not letters.
- let
- The keyword that makes a variable, as in `let price = 15;`, read as "let price be 15".
- Lifetime
- How long a reference stays valid. Rust works lifetimes out for you almost everywhere; writing them by hand is covered in the next book.
- lines / split
- Text methods: `lines()` gives each line, `split(",")` each piece between commas, `trim()` removes spaces at both ends, and `strip_prefix` returns the text after a given start if it matches. The first two are iterators.
- Linker
- A helper that joins the compiled pieces into one runnable file. Rust needs one installed: Xcode tools on macOS, `gcc` on Linux, Visual Studio's C++ tools on Windows.
- Local variable
- A parameter or variable made inside a function, which only that function can see. Values get in through arguments and out through the return value.
- loop
- `loop` repeats its block forever until `break`, while `while` checks a condition before every pass and stops when it's false.
M
- Macro
- Code that writes code, called with a `!` after its name, such as `println!`, `vec!` and `format!`.
- main function
- The function called `main`, where every Rust program starts running.
- match
- A construct that compares a value against a list of patterns and runs the code for the first one that fits. It is also an expression and must be exhaustive.
- Memory
- The place in the computer where a running program keeps its values, pictured as two areas: the stack and the heap.
- Method
- A function that belongs to a type and is called with a dot after a value, like `order.push_str(...)`. Its first parameter is `self`.
- Module
- A named group of related code made with `mod`. Its contents are private unless marked `pub`, and it can live in its own file like `src/money.rs`.
- Move
- Handing a value's ownership to another variable or a function, as in `let ticket = order;`. The old variable can't be used afterwards, which prevents freeing memory twice.
- Mutable reference
- A reference that lets the borrower change the value, written `&mut x`. You can have only one at a time, and no `&` readers at the same moment.
N
O
- Option
- An enum for a value that might be missing: `Some(value)` when there is one and `None` when there isn't. You must handle both before using the value.
- Overflow
- A number getting too big for its type, such as a `u8` above 255. Rust treats it as a bug, refusing at compile time or panicking in a normal build.
- Owner
- The variable responsible for a value. Each value has one owner at a time, and when it goes out of scope the value is dropped; these rules are called ownership.
P
- Panic
- The program stopping on an error it can't continue from, such as overflow, an out-of-bounds index or `unwrap` on an `Err`.
- Parameter
- A named input of a function, written in its parentheses with a type, which receives the argument passed in a call.
- parse
- A method that tries to turn text into another type, such as a number, and returns a `Result`. The `::<u32>` says which type you want.
- Pattern
- The shape a `match` arm tests for, such as `Some(n)`, `Grind::Espresso`, a number, a range like `2..=9` or `10 | 20`.
- Placeholder
- `{}` or `{name}` in printed text, which Rust replaces with a value. Codes like `{:02}`, `{:.2}`, `{:<16}` and `{:>4}` control digits, decimals and alignment.
- program
- A list of instructions for a computer, written in a language it understands.
- pub
- Everything in a module is private by default, usable only inside it. Marking an item `pub` makes it public so outside code can use it; struct fields need `pub` too.
- push / pop
- `push` adds an item to the end of a `Vec`, `pop` removes the last item and returns it as an `Option`, and `push_str` adds text to the end of a `String`. The variable must be `mut`.
R
- rand
- The usual crate for random numbers, since Rust's standard library has none. `rand::random_range(1..=20)` picks a random number.
- Range
- A sequence of numbers: `1..4` means 1, 2, 3 and `1..=4` includes the 4. Ranges are used in `for` loops, slices and `match` patterns.
- Reference
- A pointer to a value someone else owns, made with `&`. It lets code read the value without taking ownership.
- Release build
- A build made with `cargo build --release` that is faster and optimized but skips overflow checks. The normal debug build from `cargo run` checks and panics, so test with it.
- Remainder
- What's left after whole-number division, found with `%`, so `17 % 5` is 2. It's used with `/` to split cents into dollars and cents.
- Result
- An enum for an operation that might fail: `Ok(value)` if it worked, `Err(error)` if it didn't, with the reason.
- return
- `return` hands back a value straight away and leaves the function. The return type, written after `->`, is the type of what a function gives back; the last expression without a semicolon also returns.
- Rust Book, The
- The free official guide to Rust, which `rustup doc` opens offline.
- rust-analyzer
- The official Rust extension for VS Code that colors your code and underlines mistakes.
- rustc
- The Rust compiler's command; `rustc --version` shows which version is installed.
- Rustlings
- A collection of small exercises with broken Rust code that you fix until it compiles.
- rustup
- The official installer for Rust, which also keeps it up to date with `rustup update`.
S
- Scope
- The part of the program where a name can be used. A variable made inside a block exists only until the block's closing brace, and then its value is dropped.
- self / Self
- `self` is the first parameter of a method, the instance it was called on; `&self` reads it, `&mut self` changes it, and plain `self` takes ownership. `Self` is short for the type the `impl` is for.
- Shadowing
- Declaring a new variable with the same name as an earlier one, which hides the old one from then on, as in `let total = total + 8;`.
- Signed / unsigned
- Signed integer types (`i32`) can be negative; unsigned types (`u32`) are zero or more, which suits counts and prices in cents.
- Slice
- A borrowed view of part of a text or collection, written with a range like `&order[0..6]`. A string slice has the type `&str` and copies nothing.
- snake_case
- A naming style of lowercase words joined by underscores, like `price_per_bag`, used for variables and functions.
- Stack
- Fast memory for fixed-size values, like the order rail above a café counter. Numbers, `bool`s and `char`s live there, and each function gets its own section.
- Standard library
- The code that comes with Rust, under the name `std`, including `String`, `Vec`, `HashMap` and file reading.
- Statement
- An instruction that produces no value, such as `let coffee = 3300;`. A semicolon after an expression turns it into a statement.
- String
- Rust's owned, growable text type, whose contents live on the heap. It differs from `&str`, the borrowed kind.
- String literal
- Quoted text typed into code, such as "Bloom Café", whose type is `&str`, a borrowed view of text stored in your program. Functions that only read text should take `&str`.
- Struct
- A type that holds several named values (fields), like a `Product` with a name, price and stock flag.
T
- Terminal
- A window where you type commands. On macOS it's the Terminal app and on Windows it's PowerShell.
- to_string
- A method that turns a `&str` into a new, owned `String`, much like `String::from`.
- todo!
- A placeholder macro that compiles but panics if it is ever reached.
- Tokio
- A Rust library for async programming that provides the runtime needed to run async code. It is commonly used as the foundation for web APIs built with libraries such as Axum.
- Trait
- A named ability a type can have, such as `Debug` for printing with `{:?}` or `Copy` for being copied.
- Tuple
- A fixed-size group of values that can be different types, like `("Speckled blue mug", 1800)`. Items are read by position, such as `item.0`.
- Type
- The kind of value something is, such as a whole number, decimal, `bool` or text. It decides what you can do with the value.
- Type annotation
- A type annotation is writing a type yourself, like `let x: u32 = 5;`; type inference is Rust working it out from the value. Function parameters always need annotations.
U
- Unit type
- `()` means "no value". It's what a function returns when it has no arrow or when a stray semicolon removes its result.
- unwrap
- `unwrap()` takes the value out of an `Ok` or `Some` and panics if there isn't one; `unwrap_or(0)` gives a default you choose instead.
- use
- A line like `use money::format_cents;` that makes a shortcut so you can write the short name. It copies nothing.
V
- Variable
- A name for a value so you can use it later, made with `let`. A value is a piece of data like `15` or `"House Espresso"`.
- Variant
- One of the fixed choices an enum can be, named with the enum, like `Grind::Espresso`. A variant can carry data, such as `Van(u32)`.
- Vec
- A growable list of items of one type, such as `Vec<u32>`, kept on the heap. You make one with `Vec::new()` or the `vec!` macro.
- VS Code
- A free code editor that colors your code and underlines mistakes, used with the rust-analyzer extension.
W
- Warning
- A compiler note about something suspicious, such as a `mut` variable that never changes. The program still builds, but warnings often point at real mistakes.
- WebAssembly
- A compact binary format that lets compiled code, including Rust, run in web browsers at near-native speed. It is used to bring programs written in languages other than JavaScript to the web.