In this lesson, you will learn how to transform the comments inside your source code into professional, searchable, and hyperlinked HTML documentation using rustdoc.
What is rustdoc?
When you write a library or a complex application, you need a way to explain how your code works to other developers (or your future self). Instead of writing external manuals that quickly become outdated, Rust encourages "Doc Comments." These are special comments written directly above your code that rustdoc—the built-in Rust documentation generator—collects and formats into a beautiful website.
Using Doc Comments
To write a doc comment, you use three slashes (///) instead of the standard two (//). These triple-slash comments support Markdown, allowing you to use bold text, lists, and even code blocks.
Place these comments directly above your functions, structs, or modules:
/// Adds two numbers together.
///
/// # Examples
///
/// ```
/// let sum = my_crate::add(1, 2);
/// assert_eq!(sum, 3);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
Generating the HTML
Once you have added these comments to your project, you don't need to manually create any files. Simply open your terminal in your project’s root directory and run:
cargo doc --open
When you run this command, Cargo does three things:
- It reads your
///comments throughout your source code. - It compiles the documentation into HTML files located in the
target/docfolder. - The
--openflag automatically launches your web browser so you can view your documentation instantly.
You will see a clean, searchable interface that includes your examples, function signatures, and a tree view of your module structure. Because this is built into the Rust toolchain, every public item is automatically hyperlinked, making it easy to navigate through your entire project’s codebase.
Key Takeaway: By using /// for documentation, you can turn your source code comments into professional, hyperlinked HTML documentation with a single cargo doc --open command.