Sub topic 4
Documenting modules and crates
This chapter assumes you can write /// comments on functions and structs, split a library into modules, and run cargo doc and cargo test --doc. Here you will learn how to document containers, meaning modules and the crate itself, with inner doc comments (//!).
Outer and inner comments
A /// comment documents the item that follows it. A //! comment documents the item that contains it. Use /// for functions, structs and fields. Use //! when the thing you are describing is the file or block you are standing inside.
| Comment | Documents | Typical location |
|---|---|---|
| `///` | The next item | Directly above a function, struct, enum, `mod` declaration |
| `//!` | The enclosing item | First lines of `lib.rs`, `main.rs`, a module file, or inside `mod name { ... }` |
Both forms are shorthand for attributes: /// is #[doc = "..."] and //! is #![doc = "..."]. The inner form is an inner attribute. It must come before the items in its scope, which explains the most common error in this chapter.
Documenting the crate root
The crate root page is the first page a reader sees on docs.rs. It is built from the //! comments at the top of src/lib.rs. A good root page answers these questions:
- What is this crate for?
- What does the smallest useful example look like?
- Where should the reader go next?
//! # mycrate
//!
//! Small utilities for shapes and measurements.
//!
//! The [`shapes`] module holds the geometric types. Start there.
//!
//! # Examples
//!
//! ```
//! use mycrate::shapes::Rect;
//!
//! let r = Rect::new(3, 4);
//! assert_eq!(r.area(), 12);
//! ```
pub mod shapes;The code block is a doc test, like any other doc example. It is compiled as a separate program that depends on your crate, so it refers to the crate by name (mycrate::shapes::Rect) and can only use public items.
The # mycrate heading is optional. rustdoc already shows the crate name as the page title. Many crates skip the heading and begin with a one-sentence summary. Use headings such as # Examples for sections, as the previous chapters described.
Documenting a module in its own file
When a module lives in its own file, put the //! comment at the top of that file. Here is src/shapes.rs:
//! Geometric shapes.
//!
//! Currently this module provides [`Rect`], a rectangle with integer sides.
/// A rectangle with integer sides.
pub struct Rect {
width: u32,
height: u32,
}
impl Rect {
/// Creates a rectangle with the given width and height.
pub fn new(width: u32, height: u32) -> Self {
Rect { width, height }
}
/// Returns the area of the rectangle.
///
/// # Examples
///
/// ```
/// let r = mycrate::shapes::Rect::new(2, 5);
/// assert_eq!(r.area(), 10);
/// ```
pub fn area(&self) -> u32 {
self.width * self.height
}
}rustdoc renders the //! text at the top of the mycrate::shapes page, above the list of items. The link ` [Rect] resolves relative to the module that contains the comment, so it finds shapes::Rect` without a full path. The next chapter covers linking in detail.
Documenting inline modules and `mod` declarations
You can document a module from two places. Pick one for each module.
/// Unit conversions.
pub mod units {
/// Converts kilometres to metres.
pub fn km_to_m(km: f64) -> f64 {
km * 1000.0
}
}
pub mod time {
//! Helpers for durations.
/// Number of seconds in one minute.
pub const SECONDS_PER_MINUTE: u32 = 60;
}The units module is documented from outside with ///. The time module is documented from inside with //!. They produce the same kind of page.
For a module in another file, you could also write /// above pub mod shapes; in lib.rs. In practice, putting //! in the module's own file works better, because the description then sits next to the code it describes. If you write both, rustdoc concatenates them into one description, which is rarely what you want.
What appears where
rustdoc uses the same comment in more than one place. This is why the first paragraph matters.
The module list on a parent page shows only the first paragraph of each module's documentation. The same applies to item lists. Keep that first paragraph to one short sentence that stands alone. Put details and examples after a blank line.
Reusing a README
Many crates want the README and the crate root page to say the same thing. You can include the file instead of copying it:
#![doc = include_str!("../README.md")]
pub mod shapes;include_str! reads the file at compile time, relative to the file that contains the macro. For src/lib.rs, ../README.md points to the project root.
Check these points when you do this:
- Code blocks become doc tests. A fence with no language, or with
rust, is compiled and run bycargo test --doc. Mark shell snippets asshortext. - Install snippets. A TOML block marked
tomlis fine. An unmarked block containingcargo add mycratefails as Rust code. - Relative links break. A README link such as
[License](LICENSE)is correct on a code host but points nowhere on the docs page. - You can mix both. Use
#![doc = include_str!(...)]for the README text and add more//!lines after it. The pieces join in order.
Common errors
Inner comment after an item
An inner doc comment must come before any item in its scope. This fails:
pub fn helper() {}
//! Crate docs that are too late.The compiler reports error[E0753]: expected outer doc comment. It reads //! as a statement about the enclosing crate, but an item has already appeared. Move the comment to the top of the file, or turn it into /// on the next item.
Wrong comment kind on a module file
If you write /// at the top of shapes.rs, it documents the first item in the file, not the module. The module page has no description, and the first item gets a confusing extra paragraph. Use //! at the top of module files.
Missing blank line before the first item
Without a blank line between a //! block and the first item, the code still compiles because the two comment kinds don't conflict. The source is easy to misread, though. Leave a blank line after the //! block, as in the examples above.
Doc tests that use private items
The example in a module comment is compiled as an external program. It cannot call pub(crate) functions or private fields, even if the example sits inside the module that owns them. If an example needs private access, it is probably documenting the wrong thing. Show the public API instead.
Mismatch between the crate name and the example
Doc tests use the package's library name. If Cargo.toml has name = "my-crate", the library name is my_crate, with the hyphen replaced by an underscore. An example that says use my-crate::... does not compile. Write use my_crate::....
Practical checklist
- Start
lib.rswith a one-sentence summary, then one working example. - Give every public module a
//!comment with a one-sentence first paragraph. - Explain how the modules relate to each other at the crate root. A reader should not have to open each module to learn the layout.
- Run
cargo doc --no-deps --openand read the root page and one module list as a newcomer would. - Run
cargo test --docto confirm each example in module and crate comments still compiles and passes.
Exercise
You have a file src/parser.rs. You write /// Tools for parsing input. on the first line, followed by pub fn parse(s: &str) {}. The parser module page shows no description, and parse shows the text "Tools for parsing input." as its own documentation. What went wrong, and what is the fix?
Show answer
A /// comment documents the next item, so the text attached to parse instead of the parser module. To describe the module from inside its own file, use an inner comment at the top of the file: //! Tools for parsing input. Then parse can have its own /// comment.
Exercise
Your lib.rs starts with #![doc = include_str!("../README.md")], and cargo test --doc now fails on a block in the README that contains cargo add mycrate. How do you fix it without deleting the line?
Show answer
Every fenced block with no language (or rust) in the included README is treated as a Rust doc test. Change the fence to name a non-Rust language, such as ``` `sh `` or `` `text ```. Then rustdoc does not compile it.