The Analogy: The Margin Note and the Museum Placard
There are two completely different kinds of writing in a codebase, and conflating them is why so much documentation is useless. The first is the margin note: a line pencilled into your own copy of a book, for whoever next opens that copy. It is fast, informal, and disposable. "Careful, the author contradicts this in chapter nine." Nobody typesets a margin note, and nobody expects to find it in a library catalogue.
The second is the placard beside a museum exhibit. It is typeset, proofread, and hung on the wall for visitors who will never meet the curator. It does not say "cleaned this with a cotton swab in March"; it says what the object is, what to look at, and what it is easy to get wrong about it. The placard is part of the exhibit. If it is wrong, the museum is wrong.
Rust gives you both, and makes the difference syntactic. // is the margin note: two slashes, ignored by everything, for the next person editing this file. /// and //! are placards: cargo doc typesets them into an HTML page, they are markdown, and they are part of your crate's public surface in exactly the way the function signatures are.
Then Rust adds the thing no museum has managed. The placards are tested. Any code block inside a /// comment is compiled and run by cargo test, as a real program linked against your real library. A placard that lies fails the build. This one decision is why examples in Rust documentation are so reliably correct -- not because Rust programmers are more careful, but because a stale example is a red test, and red tests get fixed.
Syntax or Core Structure
Rust has two comment forms that are ignored, and two that are compiled into documentation. Here is all four in one file, crates/geo/src/lib.rs. The outer code block below is fenced with four backticks so that the three-backtick fences inside the doc comments survive intact -- that nesting is exactly what a real doc comment looks like.
//! A tiny geometry helper.
//!
//! `//!` is an *inner* doc comment: it documents the item it sits inside,
//! which at the top of a file means the module -- here, the crate root.
// A line comment. Everything after the slashes is ignored, and this is the
// form you will reach for almost every time.
/* A block comment, which nests in Rust:
/* this inner one is closed */ and the outer one still closes here. */
/// Returns the area of a rectangle.
///
/// The first line is the summary shown in search results and in module
/// listings, so keep it to one sentence. Everything after the blank line
/// is the long description.
///
/// # Examples
///
/// ```
/// assert_eq!(geo::area(3.0, 4.0), 12.0);
/// ```
pub fn area(width: f64, height: f64) -> f64 {
width * height
}
/// Returns the perimeter of a rectangle.
///
/// # Panics
///
/// Panics if either side is negative.
///
/// # Examples
///
/// ```
/// assert_eq!(geo::perimeter(3.0, 4.0), 14.0);
/// ```
///
/// A negative side is a bug in the caller, not an input to handle:
///
/// ```should_panic
/// geo::perimeter(-1.0, 4.0);
/// ```
pub fn perimeter(width: f64, height: f64) -> f64 {
assert!(width >= 0.0 && height >= 0.0, "sides must be non-negative");
2.0 * (width + height)
}
Three doc examples are hiding in that file, and cargo test finds all of them. The opening fences sit on lines 20, 35, and 41, which is where the test names come from:
Output (trimmed; timings, the build hash, and the path are machine-specific):
Compiling geo v0.1.0 (<repo>/crates/geo)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.42s
Running unittests src/lib.rs (target/debug/deps/geo-<hash>)
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Doc-tests geo
running 3 tests
test src/lib.rs - area (line 20) ... ok
test src/lib.rs - perimeter (line 35) ... ok
test src/lib.rs - perimeter (line 41) ... ok
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
The running 0 tests section is the unit-test binary: there is no #[cfg(test)] module in this file, so it has nothing to run. The Doc-tests geo section is the interesting one. Each example became its own tiny crate that used geo from the outside, which is why the examples write geo::area rather than a bare area -- a doc test sees your library exactly the way a user does. The three lines can print in any order, because libtest runs them on a thread pool.
Technical Depth: Six Forms, Five Headings, and a Test Runner
The comment forms
| Form | Compiled into docs? | Documents | Placement |
|---|---|---|---|
// text | no | nothing | anywhere |
/* text */ | no | nothing, and it nests | anywhere |
/// text | yes | the item that follows | immediately before an item |
//! text | yes | the item that encloses it | first thing inside a module, crate, or block |
/** text */ | yes | the item that follows | rare; /// is the convention |
/*! text */ | yes | the enclosing item | rare; //! is the convention |
The /// versus //! distinction produces a specific error when you get it backwards. A /// with no item after it is error: expected item after doc comment, and a //! that is not the first thing in its container is error: expected outer doc comment. Read them as "you documented the wrong direction".
Block comments nesting is a real difference from C, and it comes with a sharp edge: the nesting is counted by scanning for the character pairs /* and */ without regard for string literals. Wrapping /* ... */ around a region that contains the characters */ inside a string will end the comment early, in the middle of your code. This is the main reason experienced Rust programmers comment out regions with a block of // lines instead, which every editor can toggle for you.
The conventional doc headings
rustdoc requires no particular structure, but the standard library and the Rust API Guidelines use a stable set of #-level headings, and tooling looks for them by name.
| Heading | What goes under it |
|---|---|
# Examples | at least one runnable example; the first thing most readers look at |
# Panics | every condition under which the function panics |
# Errors | what each Err variant means and when it appears |
# Safety | the invariants a caller of an unsafe fn must uphold |
# Performance | complexity, allocation behaviour, anything surprising |
Three lints turn these from a convention into a check: #![warn(missing_docs)] flags undocumented public items, and clippy::missing_panics_doc and clippy::missing_errors_doc flag a function that panics or returns Result without the matching heading.
Doc tests, and the attributes on the fence
Every code block in a doc comment becomes a test. The info string after the opening fence controls what "test" means:
| Info string on the fence | Behaviour |
|---|---|
| none | compile and run; the example must pass |
no_run | compile only -- for examples that would open a socket or a file |
should_panic | must panic to pass |
compile_fail | must fail to compile; good for showing a borrow error |
ignore | not compiled at all -- almost always the wrong answer |
text | not Rust; never compiled, so use it for output and pseudocode |
ignore deserves the warning. It looks like a fix when an example stops compiling, but it silently converts a tested placard into an untested one, and nothing will ever tell you again. Reach for no_run, compile_fail, or text -- each of those still says something true about the block.
Two mechanics make short examples possible. A line beginning with # inside a doc test is hidden from the rendered page but still compiled, which is where use statements and setup go. And because the body is markdown, a line that should display a literal # must be written ##.
cargo doc and intra-doc links
cargo doc --no-deps --open builds just your crate and opens it; drop --no-deps to get your dependencies too, and add --document-private-items for an internal reference. Inside a doc comment, square brackets are intra-doc links: [Budget], [Budget::spend], [Vec], and [crate::geo::area] all resolve against the real name resolution, and the rustdoc::broken_intra_doc_links lint warns when a rename breaks one. That is strictly better than writing the name in prose, where a rename leaves the text quietly wrong.
Two attributes are worth knowing. #[doc = "..."] is what /// desugars to, which means documentation can be generated by a macro. And #![doc = include_str!("../README.md")] at the top of lib.rs puts your README on the crate's front page and doc-tests every example in it, so the file most likely to go stale becomes the file the test suite watches most closely.
Real World Example: Documenting a Retry Budget So the Docs Cannot Rot
This is crates/budget/src/lib.rs -- a small, complete, properly documented module. Every public item has a placard, the panicking constructor has a # Panics section proved by a should_panic example, the fallible method has an # Errors section, and the long example uses a hidden # use line so the visible part stays four lines.
//! Retry budgets for an upload queue.
//!
//! A [`Budget`] hands out a fixed number of retry tokens per window. It is
//! deliberately not thread-safe; wrap it in a `Mutex` if you need that.
/// A fixed pool of retry tokens.
///
/// Created with [`Budget::new`] and spent with [`Budget::spend`].
#[derive(Debug)]
pub struct Budget {
remaining: u32,
limit: u32,
}
/// Why a retry was refused.
#[derive(Debug, PartialEq)]
pub enum Refused {
/// The budget for this window is used up.
Exhausted,
/// The caller asked for more tokens than the window ever holds.
OverLimit,
}
impl Budget {
/// Creates a budget holding `limit` tokens.
///
/// # Panics
///
/// Panics if `limit` is zero, because a budget that can never be
/// spent is a configuration mistake, not a runtime condition.
///
/// # Examples
///
/// ```
/// let b = budget::Budget::new(3);
/// assert_eq!(b.remaining(), 3);
/// ```
///
/// ```should_panic
/// budget::Budget::new(0);
/// ```
pub fn new(limit: u32) -> Self {
assert!(limit > 0, "a budget of zero can never be spent");
Self { remaining: limit, limit }
}
/// Tokens still available in this window.
pub fn remaining(&self) -> u32 {
self.remaining
}
/// Spends `n` tokens and returns how many are left.
///
/// # Errors
///
/// Returns [`Refused::OverLimit`] if `n` exceeds the window total, and
/// [`Refused::Exhausted`] if fewer than `n` tokens remain.
///
/// # Examples
///
/// ```
/// # use budget::{Budget, Refused};
/// let mut b = Budget::new(3);
/// assert!(b.spend(2).is_ok());
/// assert_eq!(b.spend(2), Err(Refused::Exhausted));
/// assert_eq!(b.spend(9), Err(Refused::OverLimit));
/// assert_eq!(b.remaining(), 1);
/// ```
pub fn spend(&mut self, n: u32) -> Result<u32, Refused> {
if n > self.limit {
return Err(Refused::OverLimit);
}
match self.remaining.checked_sub(n) {
Some(left) => {
self.remaining = left;
Ok(left)
}
None => Err(Refused::Exhausted),
}
}
}
Output of cargo test --doc (trimmed; timings and the path are machine-specific):
Compiling budget v0.1.0 (<repo>/crates/budget)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.38s
Doc-tests budget
running 3 tests
test src/lib.rs - Budget::new (line 34) ... ok
test src/lib.rs - Budget::new (line 39) ... ok
test src/lib.rs - Budget::spend (line 61) ... ok
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Three of those lines are doing work that prose alone could not do. The should_panic example at line 39 is the only thing keeping the # Panics section honest: delete the assert! from new and that test fails, so the documentation and the implementation cannot drift apart. The example at line 61 asserts the exact Refused variant for both failure modes, which means the # Errors section is executable rather than aspirational. And the hidden # use budget::{Budget, Refused}; line is compiled but never rendered, so a reader of the HTML page sees a four-line example while the test still gets a complete program.
Now watch what happens when someone renames Refused::Exhausted to Refused::Empty and does not read the docs:
Output (trimmed):
running 3 tests
test src/lib.rs - Budget::new (line 34) ... ok
test src/lib.rs - Budget::new (line 39) ... ok
test src/lib.rs - Budget::spend (line 61) ... FAILED
failures:
---- src/lib.rs - Budget::spend (line 61) stdout ----
error[E0599]: no variant or associated item named `Exhausted` found for enum `Refused`
Couldn't compile the test.
failures:
src/lib.rs - Budget::spend (line 61)
test result: FAILED. 2 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out
That is the whole argument for doc tests in one transcript. The rename compiled fine -- cargo build was perfectly happy -- and the documentation is what broke the build. In a language without tested docs, that example would have sat on the crate's front page telling users about a variant that no longer exists, and the first person to notice would have been a user. Note also that the intra-doc link to Refused::Exhausted in the # Errors section breaks in the same commit, and cargo doc reports it under rustdoc::broken_intra_doc_links -- two independent alarms for one rename.
The comments that are not doc comments matter here too, and there are only two. // deliberately not thread-safe belongs on the placard because it is a fact about the API contract, so it is a //! line. Something like // checked_sub avoids the underflow panic on u32 would belong in a // margin note inside spend, because it explains a choice in the implementation and would be noise on the public page. That is the division to keep: /// says what and why for the caller, // says why for the maintainer, and neither of them says what the code plainly already says.
Common Mistakes
- Writing
//where///was meant. The text is invisible incargo doc, so the item still shows up on the page with no description at all. The two forms look nearly identical in an editor;#![warn(missing_docs)]is what catches it. - Getting the direction backwards.
///documents what follows,//!documents what encloses. A///before a closing brace giveserror: expected item after doc comment, and a//!that is not the first thing in its container giveserror: expected outer doc comment. - Silencing a broken example with
ignore. It converts a tested placard into an untested one and nothing will ever complain again.no_run,compile_fail, ortexteach keep saying something true. - Documenting panics in prose instead of under
# Panics. Readers skim for the heading, andclippy::missing_panics_doclooks for it by name. The same applies to# Errorson anything returningResult. - Restating the signature.
/// Takes a u32 and returns a u32adds nothing the declaration did not already say. Spend the line on units, invariants, or the reason the function exists. - Forgetting that doc comments are markdown.
[thing]becomes an intra-doc link and warns when it does not resolve,_name_italicises, and an unbalanced*mangles a paragraph. Wrap identifiers in backticks and the problem disappears. - Using
/* */to comment out a region. The nesting counter ignores string literals, so a*/inside a string ends your comment early and the code after it starts compiling again. Toggle//lines instead. - Leaving commented-out code as history. Git already remembers it, and unlike git it will never be updated again. Delete it.
- Expecting private items on the generated page.
cargo docdocuments the public API only; internal reference pages need--document-private-items.
Best Practices
- Open every doc comment with one sentence, then a blank
///line. That first line is the summary rustdoc puts in search results and module listings, so it has to stand alone. - Give every public item an example, and turn on
#![warn(missing_docs)]in libraries. An example is the part readers actually read, and the doc test is what keeps it true. - Use the conventional headings.
# Examples,# Panics,# Errors,# Safety,# Performance-- readers and lints both look for those exact names. - Link with intra-doc links rather than prose.
[Budget::spend]breaks loudly when the method is renamed; "see the spend method" goes quietly wrong. - Hide setup behind
#lines. The example on the page stays four lines while the compiled test remains a complete program. - *Put why in
//and what plus why it matters to the caller in///.* Implementation reasoning is for the maintainer; contracts, units, and invariants are for the user. - Doc-test your README with
#![doc = include_str!("../README.md")]. The file most likely to rot becomes the file your test suite watches hardest. - Read the rendered page before you ship.
cargo doc --no-deps --opentakes a second and reveals the mangled markdown, the missing summary line, and the item you forgot entirely.
Practice Exercises
- Promote margin notes to placards. Take a two-function module whose behaviour is described only in
//comments, convert those to///with a proper summary line and a# Examplessection each, add a//!crate-level overview, and runcargo doc --no-deps --opento confirm the summaries appear in the module listing. - Prove a panic. Write
fn checked_percent(part: u32, whole: u32) -> f64that panics whenwholeis zero, document it under# Panics, and back that section with ashould_panicdoc test plus one ordinary example. Verify withcargo test --docthat both run. - Break a placard on purpose. In the
Budgetmodule above, renameRefused::OverLimittoRefused::TooManyand runcargo test --doc. Record the failing test name and the error code, then fix the documentation rather than reverting the rename. - Make the compiler demand docs. Add
#![warn(missing_docs)]to a crate of your own and document until the build is silent, including the enum variants. Then add an intra-doc link to an item, misspell it, and record the warningcargo docproduces.