How to Generate Documentation with cargo doc

Run `cargo doc` in your project root to generate HTML documentation for your crate and its dependencies, then open the output in `target/doc/index.html`.

Run cargo doc in your project root to generate HTML documentation for your crate and its dependencies, then open the output in target/doc/index.html. By default, this command only documents your local crate; use --open to launch the browser automatically or --no-deps to skip dependency documentation.

Here is the standard workflow for generating and viewing docs:

# Generate documentation and open it in the default browser
cargo doc --open

# Generate documentation without dependencies (faster, smaller output)
cargo doc --no-deps

# Generate documentation for a specific feature flag
cargo doc --features "my-feature"

The generated files are placed in the target/doc directory. If you are working in a workspace, cargo doc documents all members by default. You can target a specific package using the -p flag:

# Document only the 'my-lib' package within a workspace
cargo doc -p my-lib --open

To ensure your documentation builds without errors in CI/CD pipelines or before merging, use the --document-private-items flag to include private items, or simply run cargo doc as a check step. If you want to enforce that all public items have documentation, add #![deny(missing_docs)] to your lib.rs or main.rs. This turns missing documentation into a compilation error, ensuring your API remains well-documented.

// lib.rs
#![deny(missing_docs)]

/// A simple function that adds two numbers.
///
/// # Examples
///
/// ```
/// let result = add(2, 3);
/// assert_eq!(result, 5);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

When running cargo doc, Rust uses the doc crate feature by default. If your documentation relies on specific conditional compilation (e.g., #[cfg(feature = "serde")]), you must pass the corresponding --features flag to ensure those items are included in the output. Without this, conditional items might be missing from the generated HTML, leading to confusion for users who enable those features.

For large projects, cargo doc can be slow because it rebuilds documentation for all dependencies. Using --no-deps significantly speeds up the process if you only care about your local code changes. Remember that the target/doc directory is not version-controlled by default; if you need to publish docs alongside your crate, you typically use cargo publish or a separate deployment step that copies the target/doc folder to a web server or GitHub Pages.