Sub topic 1
Writing doc comments with `///` and `//!`
Prerequisites
This chapter assumes basic Rust syntax, Cargo library projects, public items with pub, and Markdown. You should also know how to use assert! and assert_eq!.
Writing doc comments with `///` and `//!`
Rust uses rustdoc to turn comments into HTML documentation.
///is an outer doc comment. It documents the item immediately below it, such as a function, struct, or module.//!is an inner doc comment. It documents the enclosing crate or module.
//! # number_tools
//!
//! Small utilities for working with numbers.
/// Adds two signed integers.
///
/// This function does not check for overflow in release builds.
pub fn add(left: i32, right: i32) -> i32 {
left + right
}A module can document itself with //!:
pub mod parsing {
//! Functions for parsing user input.
/// Parses a decimal port number.
pub fn port(input: &str) -> Result<u16, std::num::ParseIntError> {
input.trim().parse()
}
}Formatting documentation with Markdown
The text after each doc-comment marker is Markdown. Use headings, lists, emphasis, links, and code blocks to make an API understandable. A heading beginning with # inside a doc comment becomes a section heading in the generated documentation.
Conventional sections
Use predictable sections so readers can quickly find important behavior.
/// Divides `n` by `d`.
///
/// # Examples
///
/// assert_eq!(number_tools::divide(8, 2), 4);
///
/// # Panics
///
/// Panics when `d` is zero.
///
/// # Safety
///
/// This function is safe because it checks the divisor before division.
pub fn divide(n: u32, d: u32) -> u32 {
assert!(d != 0, "divisor must not be zero");
n / d
}Use # Errors for a Result-returning function. Describe what causes the error and, when useful, link to its error type. Use # Safety for unsafe functions and state the caller's obligations. Document every promised panic under # Panics.
Documenting modules and crates
Put crate-level //! documentation at the top of lib.rs, before items. Put module-level //! documentation at the beginning of the module file. Use /// for public APIs inside them.
Exercise
Which comment documents the crate, and which documents a public function?
Show answer
//! documents the enclosing crate or module; /// documents the item immediately below it.