cargo doc: Turn Code Comments into a Website
cargo doc turns your Rust doc comments into a searchable HTML website for your crate and its dependencies. Use it to generate a local API reference or explore a dependency's API.
WHY IT EXISTS In a system with strong conventions like Rust, a standardized way to document code is critical. cargo doc solves the problem of generating, viewing, and sharing consistent API documentation directly from the source code, eliminating the need for separate tools and ensuring docs stay in sync with the code they describe.
THE MENTAL MODEL Think of cargo doc as a static site generator for your code's API. It reads the special /// and //! comments in your .rs files, understands their Markdown formatting, and compiles them into an interconnected set of HTML files. The result is a local version of what you see on docs.rs, complete with search, type linking, and source code viewing.
HOW IT WORKS When you run cargo doc, Cargo invokes the rustdoc compiler tool. rustdoc analyzes your crate and, by default, its dependencies. It parses doc comments, renders Markdown, and cross-links types and modules. The final HTML, CSS, and JavaScript files are placed in the target/doc directory. The --open flag simply tells Cargo to open the root index.html file in your default web browser after the build succeeds.
WHEN TO USE IT Use cargo doc constantly during development to check how your public API documentation will look. It's essential for library authors. Use it to explore the API of a new dependency locally by running it inside the dependency's cloned source directory. Use it with feature flags (--features "..." or --all-features) to see how the API changes with different configurations.
WHEN NOT TO USE IT cargo doc is for API reference documentation, not for long-form guides or tutorials. While you can write extensive module-level documentation, a separate tool like mdBook is better for narrative content. Don't rely on it as a definitive test of what is public; a tool like cargo-public-api is better for that, as cargo doc can be configured to show private items.
ONE CANONICAL EXAMPLE To build and view the documentation for your current library crate, including all its public dependencies, and have it open automatically in your browser, run: cargo doc --open. To document only your library, excluding dependencies for a faster build, run: cargo doc --lib --no-deps. If you've made changes and want a clean build, first run cargo clean --doc and then your cargo doc command.
Read the original → doc.rust-lang.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.