FAQ - Help and questions

How do I write documentation comments and build the docs with cargo doc?

#documentation#cargo#toolingpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

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.

Checked with rustc 1.93.0 and cargo 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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.
src/lib.rsrust
//! 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
    }
}
  1. 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
  1. Open target/doc/shapes/index.html, or let Cargo open it: cargo doc --no-deps --open.
  2. 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.

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet