Rust Documentation
Rust documentation is a set of web pages built from doc comments. A doc comment is a special comment above an item, like a function.
/// writes the docs
Three slashes above an item make its documentation:
/// Adds one to a number.
pub fn add_one(x: i32) -> i32 { x + 1 }The summary line
Everything before the first blank line is the summary readers see in listings:
/// Adds one to a number.
///
/// The blank line above ends the summary.
pub fn add_one(x: i32) -> i32 { x + 1 }Fields carry their own docs
A field or variant can hold its own /// comment, shown beside it on the page:
/// A user account.
pub struct Account {
/// The login name shown to others.
pub name: String,
}Block doc comments
The star forms do the same job: /** ... */ documents the item after it, /*! ... */ the item that holds it:
/** Adds one to a number. */
pub fn add_one(x: i32) -> i32 { x + 1 }A table inside a comment
Pipe tables render as real tables on the page:
/// | Input | Output |
/// |-------|--------|
/// | 2 | 3 |Doc examples use ?
/// ```
/// # fn main() -> Result<(), std::io::Error> {
/// let text = std::fs::read_to_string("notes.txt")?;
/// # Ok(())
/// # }
/// ```Example
/// Returns the larger of two values.
/// # Examples
/// assert_eq!(max_of(3, 7), 7);
fn max_of(a: i32, b: i32) -> i32 { if a > b { a } else { b } }
fn main() { println!("max = {}", max_of(3, 7)); }Key points
- Start with one summary line, then add sections: # Examples, # Panics, # Errors
- Use //! comments at the very top of src/lib.rs to document the whole crate.
- Or use them at the top of a module file to document that module.
- They describe the container that holds them, not the item that follows.
- Add a # Safety section when a function is unsafe to call.
- Say plainly what the caller must promise, so the call stays safe.
- # Arguments is the section for inputs: one bullet per argument, its name in backticks, then what the caller should pass
- Doc comments above items become the web pages that document a crate.
- docs.rs uses the same system to document all public Rust libraries.
In this example, max_of returns the larger of two numbers. Above it, the /// comments describe it and include an Examples section with a real assertion: max_of(3, 7) should equal 7. That tiny code block is a doctest — cargo test runs it. If someone later changed max_of to return the smaller value, the doctest would fail and point at the documentation. main prints max = 7, agreeing with the docs. Documentation and tests, kept honest by one mechanism.
Note
rustup is the tool that installs and updates Rust itself, including its stable, beta, and nightly versions.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
Which two commands are the standard format and lint pair?