Sub topic 6
Building and viewing docs with cargo doc
This chapter assumes you can write /// and //! comments, use Markdown inside them, and run cargo build and cargo test on a library crate. Here you will turn those comments into HTML and learn the flags that control the output.
What cargo doc does
cargo doc runs rustdoc on every crate in your build, with the right dependency paths and feature flags. rustdoc is the compiler-driven tool that reads your source and doc comments and writes HTML, CSS, JavaScript, and a search index.
The output goes to target/doc. Each crate gets its own directory, and a hyphen in the crate name becomes an underscore. For a package named my-crate, the entry page is target/doc/my_crate/index.html.
cargo doc only builds the HTML. It does not run the code examples in your comments. Running them is the job of cargo test --doc, which a later chapter covers.
A small crate to document
Use this library to try the commands. Create it with cargo new --lib mycrate, then replace src/lib.rs.
//! # mycrate
//!
//! Small utilities for working with numbers.
/// Adds two numbers.
///
/// # Examples
///
/// ```
/// use mycrate::add;
///
/// assert_eq!(add(2, 3), 5);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
/// Clamps `n` to the range `0..=100`.
fn clamp_percent(n: i32) -> i32 {
n.clamp(0, 100)
}
/// Returns `n` as a percentage between 0 and 100.
pub fn percent(n: i32) -> i32 {
clamp_percent(n)
}clamp_percent is private. Keep that in mind, because it decides what shows up in the output.
The everyday commands
The command you will use most is the one from the Topic Spine.
cargo doc --no-deps --open--no-depsdocuments only your own crates. Without it, Cargo also builds documentation for every dependency, which is slow in a project with many of them and rarely what you want while writing.--openopensindex.htmlfor the package in your browser after the build. If several browsers are installed, Cargo uses theBROWSERenvironment variable if it is set, and the system default otherwise.
Once the page opens, look for three things:
- The left sidebar lists the items in the crate, grouped by kind: functions, structs, traits, modules.
- The search box, opened with the
Skey, searches names and signatures across every documented crate. Press?to see the other shortcuts. - Each item has a
sourcelink. It shows the code the docs were generated from.
Because the output is plain static files, you can rebuild and refresh the browser. A rebuild after an edit only reprocesses crates that changed.
What is included and what is not
By default rustdoc documents public items only. Open the generated page for mycrate and you will see add and percent, but not clamp_percent. The doc comment on clamp_percent is still in the source. It is simply not rendered.
To include private items, which is useful for internal documentation and for checking your own comments:
cargo doc --no-deps --document-private-itemsPrivate items now appear and are marked as not publicly visible. Anyone using the crate from outside sees the normal output, so treat this flag as a view for maintainers.
There is one exception. When Cargo documents a binary target, it turns on --document-private-items for you. A binary has no public API for other crates to call, so the default would produce an almost empty page.
Choosing what to document
By default cargo doc documents the library and binary targets of the selected packages. These flags narrow or widen that selection.
| Flag | Effect |
|---|---|
| `--lib` | Documents only the library target |
| `--bin <name>` | Documents only the named binary |
| `-p <package>` or `--package <package>` | Documents only that workspace member |
| `--workspace` | Documents every member of the workspace |
| `--features <list>` | Enables the listed features while documenting |
| `--all-features` | Enables every feature of the selected packages |
| `--no-default-features` | Turns off the default features |
| `--target-dir <dir>` | Writes output under `<dir>/doc` instead of `target/doc` |
Features matter more than people expect. Items guarded by #[cfg(feature = "...")] are compiled out when the feature is off, and rustdoc does not see them. If your docs seem to be missing a type that exists in the source, check whether it sits behind a feature and build with --all-features.
A package that has both src/lib.rs and src/main.rs with the same name can produce a collision warning, because both targets want the same output directory. Passing --lib resolves it. You can also exclude a target permanently in Cargo.toml:
[package]
name = "mycrate"
version = "0.1.0"
edition = "2021"
[lib]
doc = true
[[bin]]
name = "mycrate-cli"
path = "src/main.rs"
doc = falseThe doc = false line on the binary leaves the command-line tool out of cargo doc output, and doc = true on the library is the default, shown here only for contrast.
Passing flags to rustdoc
Cargo does not expose every rustdoc option as its own flag. To pass the rest, use the RUSTDOCFLAGS environment variable. It applies to both cargo doc and cargo test --doc.
RUSTDOCFLAGS="-D warnings" cargo doc --no-deps-D warnings turns every rustdoc warning into an error, so the build fails on a broken link or an invalid code block attribute. This is the setup used to guard documentation quality in CI, and the lints chapter explains which warnings exist.
On Windows PowerShell, set the variable first:
$env:RUSTDOCFLAGS = "-D warnings"
cargo doc --no-depsDo not confuse RUSTDOCFLAGS with RUSTFLAGS. RUSTFLAGS goes to rustc during compilation, and RUSTDOCFLAGS goes to rustdoc. Setting the wrong one is a common reason a flag appears to do nothing.
Calling rustdoc directly
You can skip Cargo for a single file. This is handy for a quick experiment with no dependencies:
rustdoc --crate-name mycrate src/lib.rsThis writes HTML to a doc directory in the current folder. Direct use has limits. rustdoc does not know about your dependencies, features, or edition unless you pass --extern, --cfg, and --edition yourself. For anything beyond a single self-contained file, let Cargo drive it.
Common problems
- The browser shows an old version.
cargo docwrites into the same directory every time. Refresh with a hard reload. If the output looks corrupted after a toolchain upgrade, runcargo clean --docand rebuild. - The build is slow and prints many unfamiliar crate names. You left out
--no-deps. - An item is missing. It is private, behind a disabled feature, or inside a module that is not
pub. Apubitem in a private module also does not appear unless it is re-exported withpub use. --opendoes nothing in a container or over SSH. There is no browser to launch. Build the docs, then copytarget/docto a machine with one, or serve the folder with any static file server.- Links to dependency types are broken. Building with
--no-depsleaves the dependency pages out, so links into them point to docs.rs or stay unresolved, depending on the crate. This is expected. Build without--no-depsonce if you want to check those links locally.
A suggested workflow
- Write or edit doc comments.
- Run
cargo doc --no-deps --openand check how the page renders. - Run
cargo test --docto make sure the examples still pass. - Before pushing, run
RUSTDOCFLAGS="-D warnings" cargo doc --no-depsto catch warnings.
Steps 2 and 4 are build steps and step 3 is a test step. They check different things, so a project needs all three.
Exercise
You run cargo doc --no-deps in a library crate and find that a function helper with a doc comment is missing from the output, even though pub fn percent next to it is shown. Give two commands or changes that would make helper appear, and say which one affects the people who read your published docs.
Show answer
helper is most likely private (fn helper, not pub fn helper). Running cargo doc --no-deps --document-private-items shows it in your local build only, so readers of the published docs are unaffected. Changing it to pub fn helper also shows it, and that does change the public API and the published docs. (If it is already pub, check whether it sits behind a disabled Cargo feature and rebuild with --all-features, or whether its module is private and needs a pub use re-export.)
Exercise
A teammate sets RUSTFLAGS="-D warnings" and runs cargo doc, expecting a broken intra-doc link to fail the build. It does not. What should they change?
Show answer
RUSTFLAGS is passed to rustc, not rustdoc. They should use RUSTDOCFLAGS="-D warnings" cargo doc --no-deps so that rustdoc warnings, including broken links, become errors.