23.8 Generating Documentation
Rust places a strong emphasis on documentation, and Cargo makes generating and viewing it easy.
23.8.1 Documentation Comments
Rust uses specific comment styles for documentation, written in Markdown:
///
: Outer documentation comment, documenting the item following it (function, struct, enum, module, etc.).//!
: Inner documentation comment, documenting the item containing it (typically used at the top oflib.rs
ormain.rs
to document the entire crate, or inside amod { ... }
block to document the module).
#![allow(unused)] fn main() { //! This crate provides utility functions for string manipulation. //! Use `add_prefix` to prepend text. /// Adds a prefix to the given string. /// /// # Examples /// /// ``` /// let result = my_string_utils::add_prefix("world", "hello "); /// assert_eq!(result, "hello world"); /// ``` /// /// # Panics /// /// This function does not panic. /// /// # Errors /// /// This function does not return errors. pub fn add_prefix(s: &str, prefix: &str) -> String { format!("{}{}", prefix, s) } }
Good documentation explains the purpose, parameters, return values, potential errors or panics, usage examples (which double as doc tests), and safety considerations (especially for unsafe
code).
23.8.2 cargo doc
The cargo doc
command invokes the rustdoc
tool to extract these comments and generate HTML documentation.
# Generate docs for your crate and dependencies
cargo doc
# Generate docs and open the main page in a browser
cargo doc --open
# Generate docs only for your crate (not dependencies)
cargo doc --no-deps
The generated documentation, located in target/doc
, provides a navigable interface for your crate’s public API and the APIs of its dependencies.
23.8.3 Re-exporting for API Design
As mentioned in Chapter 17, you can use pub use
statements to re-export items from modules or dependencies, creating a cleaner and more stable public API surface for your library. This also affects how the API appears in the generated documentation.