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#
- Write the comments. Put a runnable example under a
# Examplesheading.
//! 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
}
}- Build the HTML.
--no-depsskips the documentation of your dependencies, which makes it much quicker.
> 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- Open
target/doc/shapes/index.html, or let Cargo open it:cargo doc --no-deps --open. - The example block is a test as well.
cargo test --doccompiles and runs it:
> 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.