23.8 Generating Documentation

Rust places a strong emphasis on documentation, and Cargo makes generating and viewing it easy for your package’s crates.

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.) within a crate.
  • //!: Inner documentation comment, documenting the item containing it (typically used at the top of lib.rs or main.rs to document the entire crate, or inside a mod { ... } block to document the module).
#![allow(unused)]
fn main() {
//! This package contains a crate that provides utility functions for string
//! manipulation. Use `add_prefix` from the `my_string_utils` crate 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 for your package’s public crates.

# Generate documentation (output in target/doc/)
cargo doc

# Generate documentation and open the main page in a browser
cargo doc --open

# Generate docs only for your package's own crates (not dependencies)
cargo doc --no-deps

The generated documentation, located in target/doc, provides a navigable interface for your package’s public API (the public items within its library crate(s)) and the APIs of its dependency packages.

23.8.3 Re-exporting for API Design

As mentioned in Chapter 17, you can use pub use statements within a library crate to re-export items from modules or dependency crates, creating a cleaner and more stable public API surface for your library package. This also affects how the API appears in the generated documentation.