Rust - Comments & Documentation

Overview

Estimated time: 25–35 minutes

Learn about Rust's commenting system, including regular comments, documentation comments, and how to generate beautiful documentation with rustdoc. Master the art of writing clear, maintainable code with proper documentation.

Learning Objectives

Prerequisites

Comment Types

Single-Line Comments

Use // for single-line comments. These are ignored by the compiler and used for explaining code:

fn main() {
    // This is a single-line comment
    let x = 5; // Comments can be at the end of a line
    
    // You can have multiple single-line comments
    // to explain complex logic
    let y = x * 2;
}

Multi-Line Comments

Use /* */ for multi-line comments. While less common in Rust, they're useful for temporarily disabling blocks of code:

fn main() {
    /*
     * This is a multi-line comment.
     * It can span multiple lines.
     * Useful for larger explanations.
     */
    let x = 10;
    
    /* 
    let y = 20; // This code is commented out
    let z = x + y;
    */
}

Documentation Comments

Outer Documentation Comments

Use /// for documentation comments that describe the item that follows:

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

/// A person with a name and age.
/// 
/// # Examples
/// 
/// ```
/// let person = Person::new("Alice", 30);
/// println!("{}", person.name);
/// ```
pub struct Person {
    /// The person's name
    pub name: String,
    /// The person's age in years
    pub age: u32,
}

Inner Documentation Comments

Use //! for documentation comments that describe the containing item (module, crate, etc.):

//! This module provides utilities for geometric calculations.
//! 
//! It includes functions for calculating areas, perimeters,
//! and other geometric properties.

/// Calculate the circumference of a circle
pub fn circle_circumference(radius: f64) -> f64 {
    2.0 * std::f64::consts::PI * radius
}

Documentation Sections

Common Documentation Sections

Rust documentation commonly uses these sections:

/// Brief description of the function.
/// 
/// Longer description with more details about what
/// the function does and when to use it.
/// 
/// # Arguments
/// 
/// * `param1` - Description of the first parameter
/// * `param2` - Description of the second parameter
/// 
/// # Returns
/// 
/// Description of what the function returns.
/// 
/// # Examples
/// 
/// ```
/// let result = my_function(1, 2);
/// assert_eq!(result, 3);
/// ```
/// 
/// # Panics
/// 
/// This function panics if the input is negative.
/// 
/// # Errors
/// 
/// This function returns an error if the file cannot be read.
/// 
/// # Safety
/// 
/// This function is unsafe because it dereferences raw pointers.
fn my_function(param1: i32, param2: i32) -> i32 {
    param1 + param2
}

Generating Documentation

Using rustdoc

Generate HTML documentation from your doc comments:

# Generate documentation for your crate
cargo doc

# Generate and open documentation in browser
cargo doc --open

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

Testing Documentation Examples

Rust can test the code examples in your documentation:

# Run documentation tests
cargo test --doc

# Example that will be tested
/// Adds two numbers together.
/// 
/// # Examples
/// 
/// ```
/// assert_eq!(add(2, 3), 5);
/// ```
fn add(a: i32, b: i32) -> i32 {
    a + b
}

Best Practices

Writing Good Documentation

/// Divides two numbers.
/// 
/// This function performs floating-point division. For integer division,
/// use the `/` operator directly.
/// 
/// # Arguments
/// 
/// * `dividend` - The number to be divided
/// * `divisor` - The number to divide by
/// 
/// # Returns
/// 
/// The result of the division as a floating-point number.
/// 
/// # Panics
/// 
/// This function will panic if `divisor` is zero.
/// 
/// # Examples
/// 
/// ```
/// let result = divide(10.0, 2.0);
/// assert_eq!(result, 5.0);
/// ```
fn divide(dividend: f64, divisor: f64) -> f64 {
    if divisor == 0.0 {
        panic!("Cannot divide by zero!");
    }
    dividend / divisor
}

Markdown in Documentation

Formatting Options

Doc comments support Markdown formatting:

/// This function demonstrates **Markdown** formatting.
/// 
/// You can use:
/// - *Italic text*
/// - **Bold text**
/// - `Code spans`
/// - [Links](https://doc.rust-lang.org/)
/// 
/// ## Code Blocks
/// 
/// ```rust
/// let x = 42;
/// println!("The answer is {}", x);
/// ```
/// 
/// ## Lists
/// 
/// 1. First item
/// 2. Second item
/// 3. Third item
fn documented_function() {
    println!("Hello, documentation!");
}

Common Pitfalls

Mistakes to Avoid

Checks for Understanding

  1. What's the difference between // and /// comments?
  2. When would you use //! instead of ///?
  3. How do you generate HTML documentation from doc comments?
  4. What happens when you run cargo test --doc?
Answers
  1. // are regular comments ignored by rustdoc; /// are documentation comments that appear in generated docs
  2. Use //! for inner documentation that describes the containing module or crate
  3. Use cargo doc or cargo doc --open to generate and view HTML documentation
  4. It runs the code examples in documentation comments as tests to ensure they work correctly

← PreviousNext →