Sub topic 1
Writing doc comments with /// and //!
Rust has two kinds of documentation comments. Both are written in Markdown, and rustdoc turns them into HTML pages. This chapter covers the syntax, what each kind attaches to, and the mistakes people commonly make. Doc tests, links, and the other features have their own chapters.
Prerequisites
This chapter assumes you can:
- Write basic Rust: functions, structs, enums,
implblocks, and modules withpubvisibility. - Create and build a library crate with Cargo.
- Read simple Markdown (paragraphs, lists, inline code).
Two kinds of doc comments
An ordinary comment starts with // and is discarded by the compiler. A doc comment is kept and attached to a piece of code as documentation. There are two forms:
| Form | Name | Documents |
|---|---|---|
| `/// text` | Outer doc comment | The item that comes after it |
| `//! text` | Inner doc comment | The item that contains it |
Use /// for functions, structs, enums, fields, and most other things. Use //! for modules and crates, where you describe the thing you are inside.
//! Utilities for temperature conversion.
/// A temperature scale.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Scale {
/// Degrees Celsius.
Celsius,
/// Degrees Fahrenheit.
Fahrenheit,
}
/// A temperature reading.
pub struct Reading {
/// The numeric value.
pub value: f64,
/// The scale that `value` is expressed in.
pub scale: Scale,
}
impl Reading {
/// Creates a reading from a value and a scale.
pub fn new(value: f64, scale: Scale) -> Self {
Self { value, scale }
}
/// Returns the value converted to Celsius.
pub fn to_celsius(&self) -> f64 {
match self.scale {
Scale::Celsius => self.value,
Scale::Fahrenheit => (self.value - 32.0) * 5.0 / 9.0,
}
}
}Save this as src/lib.rs. The //! line on top documents the crate. Every /// line documents the item right below it, including enum variants and struct fields.
How a doc comment is stored
A doc comment is syntax sugar for the #[doc] attribute. These two functions have the same documentation:
/// Adds one to `x`.
pub fn inc_a(x: i32) -> i32 {
x + 1
}
#[doc = " Adds one to `x`."]
pub fn inc_b(x: i32) -> i32 {
x + 1
}The attribute form shows a detail. The text after /// includes the leading space, and rustdoc removes the indentation shared by all lines. This means you write /// text with a space and the space has no effect on the output.
Inner comments work the same way. //! expands to #![doc = "..."], where the ! marks an attribute that applies to the enclosing item. Later chapters cover #[doc] for cases like hiding items or adding search aliases.
There are also block forms: /** ... */ for outer and /*! ... */ for inner. They are valid but rare. The community style, and what rustfmt and Clippy expect, is line comments.
Where doc comments can go
Doc comments attach to items and to parts of items:
- Functions, methods, and associated functions
- Structs, enums, unions, and type aliases
- Struct fields and enum variants
- Traits, trait methods, and associated types and constants
- Constants, statics, and modules
implblocks (these show up in the type's documentation)macro_rules!macros
Documentation on trait methods is inherited by implementations that do not provide their own, so document the trait method once.
You can put attributes between the comment and the item. Both of the following work, but the first is the usual style because the comment reads as the first thing about the item:
/// A point in 2D space.
#[derive(Debug, Clone, Copy)]
pub struct Point {
/// Horizontal position.
pub x: f64,
/// Vertical position.
pub y: f64,
}Documenting modules and the crate root
An inner comment must appear before any item in the module or file it describes. For the crate, that is the top of src/lib.rs. For a file module, it is the top of that file. For an inline module, it is the first thing inside the braces:
/// Length units.
pub mod units {
//! Types that represent physical lengths.
//!
//! Each type wraps a plain `f64`.
/// A length in meters.
pub struct Meters(pub f64);
}Here the module has both a /// comment from outside and a //! comment from inside. rustdoc joins them. In practice, pick one place per module. For file modules, //! at the top of the file is the usual choice. For inline modules, /// before the mod line is usually easier to read.
Writing the first line
The first paragraph of a doc comment has a special job. rustdoc shows it as the summary in item listings, search results, and module overviews. Write it as one short sentence in the third person that says what the item does:
/// Returns the larger of two values.
///
/// If the values are equal, returns the second one. This matches
/// the behavior of [`Ord::max`].
pub fn larger<T: Ord>(a: T, b: T) -> T {
if a > b { a } else { b }
}Leave a blank /// line after the summary. Without it, the summary and the next sentence merge into one long paragraph that gets truncated in listings.
Building the result
To see your comments as HTML, run:
cargo doc --no-deps --open--no-deps skips documentation for dependencies, which keeps the build fast. --open opens the result in your browser. The chapter on tooling covers the options in detail.
Common errors
Doc comments in the wrong place. Doc comments apply to items, not to statements or expressions. A /// comment on a let statement or on a bare expression produces the unused_doc_comments warning, because nothing can display it. Use a regular // comment for notes inside function bodies:
pub fn double(x: i32) -> i32 {
// Plain comment: explains the code, does not appear in the docs.
x * 2
}A /// comment with nothing after it. If a /// comment ends a block or file with no item following it, the compiler reports "expected item after doc comment". This often happens after you comment out or delete the item below. Delete the comment or restore the item.
//! after an item. An inner comment must come before the items in its scope. Placing //! after a function in the same file gives the error "expected outer doc comment". The fix is to move it to the top, or change it to /// if it was meant for the next item.
Four slashes. //// is a regular comment, not a doc comment. This is deliberate, so decorative separator lines like //////////// do not leak into the docs.
Documenting the wrong thing. Putting //! text inside a function body does not document the function in the way you might expect. Use /// above the function instead.
Style conventions
The Rust API guidelines recommend a few habits that keep documentation consistent across crates:
- Start with a one-line summary in the third person: "Returns...", "Creates...", not "Return..." or "This function returns...".
- Document every public item, including fields and variants.
- Use
//!on the crate root to explain what the crate is for and show a short example. - Put specifics (errors, panics, safety requirements) in headed sections, which the next chapters cover.
Exercise
A file contains a function fn parse() followed on the next line by //! Parses the input. The compiler rejects the file. Why, and what are two valid fixes?
Show answer
An inner doc comment (//!) must appear before the items of the scope it documents. After fn parse() it is out of place, so the compiler reports "expected outer doc comment". One fix is to change it to /// and place it directly above fn parse() so it documents that function. The other, if it was meant to describe the module or crate, is to move it to the top of the file, before any items.
Exercise
What does /// Adds one. expand to as an attribute, and what does //! Utilities. expand to?
Show answer
/// Adds one. expands to #[doc = " Adds one."], applied to the following item. //! Utilities. expands to #![doc = " Utilities."]. The ! makes it an inner attribute that applies to the enclosing module or crate.