← Back to Rust Course | Chapter 15: Cargo, Testing & Best Practices | Lesson 7 of 8

Documentation Comments

Documentation comments are the friendly explanations you write above your code that turn into a real, browsable manual.

Documenting a Function with ///

Placing /// comments directly above a function describes what it does, and cargo doc uses this text to generate that function's documentation page.

Example: Documenting a Function with ///

markup
/// Calculates the area of a rectangle given its width and height.
fn area(width: f64, height: f64) -> f64 {
    width * height
}

fn main() {
    println!("Area: {}", area(3.0, 4.0));
}

Documenting a Module with //!

//! comments, usually placed at the very top of a file, document the enclosing item itself (like the whole module) rather than whatever code follows them.

Example: Documenting a Module with //!

markup
//! This module provides simple geometry helper functions.

fn perimeter(width: f64, height: f64) -> f64 {
    2.0 * (width + height)
}

fn main() {
    println!("Perimeter: {}", perimeter(3.0, 4.0));
}

Including a Usage Example

Good documentation comments often include a fenced code example showing how to call the function, which is both helpful to readers and doubles as an automatically-run doc test.

Example: Including a Usage Example

markup
/// Converts Celsius to Fahrenheit.
///
/// ```
/// let f = my_project::to_fahrenheit(0.0);
/// assert_eq!(f, 32.0);
/// ```
pub fn to_fahrenheit(celsius: f64) -> f64 {
    celsius * 9.0 / 5.0 + 32.0
}

fn main() {
    println!("{}", to_fahrenheit(0.0));
}

Generating HTML Docs

cargo doc --open builds a full HTML documentation site from all the doc comments in a project and opens it directly in your web browser.

Example: Generating HTML Docs

bash
cargo doc --open

⚠️ Run this command in your terminal.

Common Mistakes
  1. Using regular // comments when /// is needed for the comment to actually be picked up as documentation by cargo doc.
  2. Forgetting //! documents the enclosing item (like a whole module) rather than the next item that follows it.
  3. Not including a runnable example in doc comments for public functions, missing an easy opportunity for a free doc test.
Chapter Summary
  • /// documents the item immediately following it, such as a function or struct.
  • //! documents the enclosing item itself, commonly used at the top of a module or crate.
  • cargo doc --open generates HTML documentation from these comments and opens it in a browser.
  • Well-written doc comments often include a runnable example, which doubles as a doc test.
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.