Rust Documentation

Creating comprehensive and helpful documentation

📚 What is Rust Documentation?

Rust documentation uses special comments and attributes to generate beautiful, searchable HTML documentation. It includes examples, tests, and cross-references to create comprehensive guides for your code.


/// Calculates the area of a rectangle.
/// 
/// # Examples
/// ```
/// let area = calculate_area(5.0, 3.0);
/// assert_eq!(area, 15.0);
/// ```
pub fn calculate_area(width: f64, height: f64) -> f64 {
    width * height
}
                                    

Documentation Types

📝

API Documentation

Document functions, structs, and modules

/// This is API documentation
pub fn my_function() {}
📖

Crate Documentation

High-level crate overview and guides

//! This is crate documentation
//! # My Crate
💡

Code Examples

Runnable examples in documentation

/// ```
/// assert_eq!(add(2, 3), 5);
/// ```
🔗

Cross-references

Link between related items

/// See also [`other_function`]
pub fn my_function() {}

🔹 Basic Documentation Comments

Use /// for item documentation and //! for module/crate documentation:

//! # My Math Library
//! 
//! This crate provides basic mathematical operations.
//! 
//! ## Quick Start
//! 
//! ```
//! use my_math::add;
//! 
//! let result = add(2, 3);
//! assert_eq!(result, 5);
//! ```

/// Adds two numbers together.
/// 
/// This function takes two integers and returns their sum.
/// 
/// # Arguments
/// 
/// * `a` - The first number
/// * `b` - The second number
/// 
/// # Examples
/// 
/// ```
/// use my_math::add;
/// 
/// let result = add(2, 3);
/// assert_eq!(result, 5);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

/// A point in 2D space.
/// 
/// # Examples
/// 
/// ```
/// use my_math::Point;
/// 
/// let point = Point::new(1.0, 2.0);
/// assert_eq!(point.x, 1.0);
/// assert_eq!(point.y, 2.0);
/// ```
pub struct Point {
    /// The x coordinate
    pub x: f64,
    /// The y coordinate  
    pub y: f64,
}

impl Point {
    /// Creates a new point.
    /// 
    /// # Arguments
    /// 
    /// * `x` - The x coordinate
    /// * `y` - The y coordinate
    /// 
    /// # Examples
    /// 
    /// ```
    /// use my_math::Point;
    /// 
    /// let point = Point::new(3.0, 4.0);
    /// ```
    pub fn new(x: f64, y: f64) -> Self {
        Point { x, y }
    }
}

🔹 Documentation Sections

Use standard sections to organize documentation:

/// Divides two numbers.
/// 
/// # Arguments
/// 
/// * `dividend` - The number to be divided
/// * `divisor` - The number to divide by
/// 
/// # Returns
/// 
/// Returns `Ok(result)` if successful, or `Err(message)` if division by zero.
/// 
/// # Examples
/// 
/// ```
/// use my_math::divide;
/// 
/// let result = divide(10.0, 2.0).unwrap();
/// assert_eq!(result, 5.0);
/// ```
/// 
/// # Errors
/// 
/// This function will return an error if `divisor` is zero:
/// 
/// ```should_panic
/// use my_math::divide;
/// 
/// divide(10.0, 0.0).unwrap(); // This will panic
/// ```
/// 
/// # Panics
/// 
/// This function does not panic directly, but `.unwrap()` will panic on error.
/// 
/// # Safety
/// 
/// This function is safe to call with any f64 values.
pub fn divide(dividend: f64, divisor: f64) -> Result<f64, String> {
    if divisor == 0.0 {
        Err("Cannot divide by zero".to_string())
    } else {
        Ok(dividend / divisor)
    }
}

🔹 Code Examples and Tests

Documentation examples are automatically tested:

/// Calculates factorial of a number.
/// 
/// # Examples
/// 
/// Basic usage:
/// 
/// ```
/// use my_math::factorial;
/// 
/// assert_eq!(factorial(5), 120);
/// assert_eq!(factorial(0), 1);
/// ```
/// 
/// You can also use it in expressions:
/// 
/// ```
/// use my_math::factorial;
/// 
/// let result = factorial(4) * 2;
/// assert_eq!(result, 48);
/// ```
/// 
/// # Note
/// 
/// This example won't run (compilation only):
/// 
/// ```no_run
/// use my_math::factorial;
/// 
/// // This would take too long to run in tests
/// let big = factorial(100);
/// ```
/// 
/// This example should fail to compile:
/// 
/// ```compile_fail
/// use my_math::factorial;
/// 
/// // This won't compile - factorial expects u32
/// factorial("not a number");
/// ```
pub fn factorial(n: u32) -> u32 {
    match n {
        0 | 1 => 1,
        _ => n * factorial(n - 1),
    }
}

🔹 Generating Documentation

Use Cargo to generate and view documentation:

# Generate documentation
cargo doc

# Generate and open in browser
cargo doc --open

# Include private items
cargo doc --document-private-items

# Generate for dependencies too
cargo doc --no-deps

# Generate documentation tests
cargo test --doc

Generated files:

target/doc/my_crate/index.html

target/doc/my_crate/fn.add.html

target/doc/my_crate/struct.Point.html

🔹 Advanced Documentation Features

Use links, attributes, and special formatting:

/// A mathematical calculator.
/// 
/// This struct provides various mathematical operations.
/// See [`Calculator::add`] for addition and [`Calculator::multiply`] for multiplication.
/// 
/// # Related
/// 
/// * [`Point`] - For geometric calculations
/// * [`divide`] - For standalone division
/// 
/// # Examples
/// 
/// ```
/// use my_math::Calculator;
/// 
/// let calc = Calculator::new();
/// let result = calc.add(2, 3);
/// assert_eq!(result, 5);
/// ```
#[derive(Debug)]
pub struct Calculator {
    /// The current value stored in the calculator
    pub value: f64,
}

impl Calculator {
    /// Creates a new calculator.
    /// 
    /// The calculator starts with a value of 0.0.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use my_math::Calculator;
    /// 
    /// let calc = Calculator::new();
    /// assert_eq!(calc.value, 0.0);
    /// ```
    pub fn new() -> Self {
        Calculator { value: 0.0 }
    }
    
    /// Adds two numbers.
    /// 
    /// This is a simple addition operation.
    /// 
    /// # Arguments
    /// 
    /// * `a` - First number
    /// * `b` - Second number
    /// 
    /// # Examples
    /// 
    /// ```
    /// use my_math::Calculator;
    /// 
    /// let calc = Calculator::new();
    /// let result = calc.add(2, 3);
    /// assert_eq!(result, 5);
    /// ```
    pub fn add(&self, a: i32, b: i32) -> i32 {
        a + b
    }
}

🔹 Documentation Attributes

Control documentation generation with attributes:

// Hide from documentation
#[doc(hidden)]
pub fn internal_function() {
    // This won't appear in generated docs
}

/// This function has a custom title.
#[doc(alias = "plus")]
#[doc(alias = "sum")]
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

/// A configuration struct.
/// 
/// # Examples
/// 
/// ```
/// use my_crate::Config;
/// 
/// let config = Config::default();
/// ```
#[doc(cfg(feature = "config"))]
pub struct Config {
    pub debug: bool,
}

// Inline documentation from file
#[doc = include_str!("../README.md")]
pub struct MyStruct;

Useful attributes:

  • #[doc(hidden)]: Hide from documentation
  • #[doc(alias = "name")]: Add search aliases
  • #[doc(cfg(...))]: Show feature requirements
  • #[doc = include_str!(...)]: Include external files

🧠 Test Your Knowledge

Which comment style is used for documenting individual items?