Rust Documentation (rustdoc)

Overview

Rust has documentation built into the language. Code and docs live together.

Quick Start: Test It Now

Create test project
cd /tmp
cargo new rust-test
cd rust-test
Write documented code (src/main.rs)
//! # My Test Crate
//!
//! Learning rustdoc.

/// Checks if IP is RFC1918 private.
///
/// # Examples
///
/// ```
/// assert!(rust_test::is_private_ip("10.50.1.50"));
/// ```
pub fn is_private_ip(ip: &str) -> bool {
    ip.starts_with("10.") || ip.starts_with("192.168.")
}

fn main() {
    println!("Private: {}", is_private_ip("10.50.1.50"));
}
Run it
cargo run                 # Execute the program
cargo doc --open          # Generate docs, open in browser
cargo test --doc          # Run the examples as tests

Learning loop: Write code → Document it → cargo test --doccargo doc --open → Repeat

Doc Comment Syntax

Outer doc comments (document the NEXT item)
/// This documents the function below
///
/// # Examples
///
/// ```
/// let result = add(2, 3);
/// assert_eq!(result, 5);
/// ```
fn add(a: i32, b: i32) -> i32 {
    a + b
}
Inner doc comments (document the ENCLOSING item)
//! This documents the module/crate itself
//!
//! # My Crate
//!
//! This crate does amazing things.

Markdown in Doc Comments

/// # Heading
///
/// Regular paragraph text.
///
/// - Bullet point
/// - Another point
///
/// `inline code` and **bold** and *italic*
///
/// ```
/// // Code block - THIS RUNS AS A TEST
/// let x = 5;
/// ```
///
/// [Link text](https://example.com)

Common Sections

/// Brief one-line description.
///
/// Longer description if needed.
///
/// # Arguments
///
/// * `name` - Description of this parameter
/// * `count` - Description of this parameter
///
/// # Returns
///
/// Description of return value
///
/// # Examples
///
/// ```
/// // Example code here
/// ```
///
/// # Panics
///
/// Conditions that cause this function to panic
///
/// # Errors
///
/// Errors this function can return (for Result types)
///
/// # Safety
///
/// For unsafe functions - what invariants must be upheld

cargo doc Commands

Generate and open documentation
cargo doc --open
Generate docs including dependencies
cargo doc --open --document-private-items
Generate docs for specific package in workspace
cargo doc --package my-crate --open
Check doc coverage (nightly)
RUSTDOCFLAGS='-Z unstable-options --show-coverage' cargo +nightly doc

Doctests

Code in doc comments runs as tests:

/// Adds two numbers.
///
/// # Examples
///
/// ```
/// assert_eq!(mylib::add(2, 2), 4);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}
Run doctests
cargo test --doc
Doctest that should panic
/// # Examples
///
/// ```should_panic
/// panic!("This is expected");
/// ```
Doctest that should fail to compile
/// # Examples
///
/// ```compile_fail
/// let x: i32 = "not a number";
/// ```
Hide setup code in doctests
/// # Examples
///
/// ```
/// # // Lines starting with # are hidden in docs but still run
/// # fn setup() -> i32 { 42 }
/// let value = setup();
/// assert_eq!(value, 42);
/// ```
Doctest that doesn’t run (display only)
/// # Examples
///
/// ```ignore
/// // This code is shown but not executed
/// complex_setup_that_cant_run_in_test();
/// ```

Module and Crate Documentation

Crate root (lib.rs or main.rs)
//! # My Crate
//!
//! `my_crate` provides utilities for doing X.
//!
//! ## Quick Start
//!
//! ```
//! use my_crate::do_thing;
//! do_thing();
//! ```
Module documentation
//! Networking utilities.
//!
//! This module contains TCP and UDP helpers.

pub mod tcp;
pub mod udp;

Linking in Docs

Link to other items
/// See also [`OtherStruct`] and [`module::function`].
///
/// Returns [`Result<T, Error>`].
Explicit link paths
/// Link to [`crate::module::Type`]
/// Link to [`self::sibling_function`]
/// Link to [`super::parent_module`]

Attributes

Hide from documentation
#[doc(hidden)]
pub fn internal_function() {}
Add to docs without showing signature
#[doc = include_str!("../README.md")]
pub struct MyStruct;
Alias in docs
#[doc(alias = "old_name")]
pub fn new_name() {}

Output Location

Generated docs go to:

target/doc/
└── my_crate/
    ├── index.html      # Crate root
    ├── fn.add.html     # Function docs
    ├── struct.Foo.html # Struct docs
    └── ...