23.8 Creating Documentation
Cargo integrates with Rust’s documentation system. When publishing or simply wanting a thorough API reference, use Rust’s doc comments and the cargo doc
command.
23.8.1 Documentation Comments
Rust supports two primary forms of documentation comments:
///
: Public-facing documentation for the item immediately following (functions, structs, etc.).//!
: At the crate root (e.g., top oflib.rs
), describing the entire crate.
Doc comments use Markdown formatting. Code blocks in doc comments become “doc tests,” compiled and run automatically via cargo test
. Good documentation should explain:
- The function’s or type’s purpose
- Parameters and return values
- Error conditions or potential panics
- Safe/unsafe usage details
23.8.2 cargo doc
Run:
cargo doc
This generates HTML documentation in target/doc
. Open it automatically in a browser with:
cargo doc --open
It includes documentation for both your crate and its dependencies, providing an easy way to browse APIs.
23.8.3 Reexporting Items for a Streamlined API
Large projects or libraries that wrap 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 more accessible in the generated docs
We introduced reexports in Chapter 17.