23.8 Creating Documentation
Cargo integrates with Rust’s documentation system. When publishing or just wanting a solid API reference, leverage Rust’s doc comments and the cargo doc
command.
23.8.1 Documentation Comments
Two primary forms of documentation comments exist in Rust:
///
: Creates public-facing documentation for the item immediately following (functions, structs, etc.).//!
: Used at the crate root (e.g., top oflib.rs
) for describing the entire crate.
Doc comments support Markdown formatting. Code blocks included in doc comments become “doc tests,” which compile and run automatically via cargo test
. Good documentation typically explains:
- What the function or type does
- Parameters and return values
- Error conditions or panics
- Safe/unsafe usage details
23.8.2 cargo doc
Running:
cargo doc
Generates HTML documentation in target/doc
. Open it in your web browser automatically with:
cargo doc --open
This includes docs for both your crate and its dependencies, letting you browse APIs easily.
23.8.3 Reexporting Items for a Streamlined API
Large projects or libraries that wrap functionality from multiple crates often use reexports to simplify their public API. Reexporting can:
- Provide shorter or more direct paths to types and functions
- Make your library’s structure easier to navigate in the generated docs
We introduced reexports in Chapter 17.