# How do I write documentation comments and build the docs with cargo doc?
Source: https://ruststudio.org/community/t/121/how-do-i-write-documentation-comments-and-build-the-docs-with-cargo-doc
Author: Ruststudio Team (staff) | Published: 2026-12-05 | Updated: 2026-12-05 | Checked with: rustc 1.93.0 and cargo 1.93.0, Windows 11
Category: Help and questions | Kind: FAQ | Tags: documentation, cargo, tooling | Views: 0

## Short answer
Write /// above an item for its documentation and //! at the top of a file for the module or crate. Markdown works, and code blocks in the comments are compiled as tests. Run cargo doc --no-deps to build an HTML site for your crate, and cargo doc --open to view it.

## Answer
## Answer
Rust documentation lives in the source as special comments. `///` documents the item that follows it, `//!` documents the file or crate it is written in. The text is Markdown. `cargo doc` turns it into a website with search, and the same comments feed editor hover texts.

## How to do it
1. Write the comments. Put a runnable example under a `# Examples` heading.

```rust title=src/lib.rs
//! Small helpers for rectangles.

/// A rectangle with a width and a height.
///
/// # Examples
///
/// ```
/// let r = shapes::Rect::new(3, 4);
/// assert_eq!(r.area(), 12);
/// ```
pub struct Rect {
    width: u32,
    height: u32,
}

impl Rect {
    /// Creates a rectangle.
    pub fn new(width: u32, height: u32) -> Rect {
        Rect { width, height }
    }

    /// The area in square units.
    pub fn area(&self) -> u32 {
        self.width * self.height
    }
}
```

2. Build the HTML. `--no-deps` skips the documentation of your dependencies, which makes it much quicker.

```text
> cargo doc --no-deps
 Documenting shapes v0.1.0 (C:\dev\docd)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.82s
   Generated C:\dev\docd\target\doc\shapes\index.html
all.html
index.html
sidebar-items.js
struct.Rect.html
```

3. Open `target/doc/shapes/index.html`, or let Cargo open it: `cargo doc --no-deps --open`.
4. The example block is a test as well. `cargo test --doc` compiles and runs it:

```text
> cargo test --doc
test src\lib.rs - Rect (line 7) ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; 
```

## Why it works
`rustdoc` is the tool behind `cargo doc`; it reads the same syntax tree the compiler does, so links such as [`Rect`] resolve to real items, and a renamed function breaks a doc test instead of leaving a wrong example behind.

## Common mistakes
- Putting `///` on a private item and wondering why it is not in the HTML. Private items are left out unless you add `--document-private-items`.
- Using `//` (an ordinary comment) instead of `///`.
- Writing an example that needs a network or a file. Hide setup lines by starting them with `# ` inside the block: they run but are not shown.

## In Ruststudio
Run > Build Documentation runs `cargo doc` for the project.
