Sub topic 3
Conventional sections: Examples, Panics, Errors, Safety
This chapter assumes you can write /// comments, know basic Markdown, and can run cargo test --doc. It covers four section headings that Rust libraries use by convention. rustdoc does not treat them specially. They are Markdown headings that readers and Clippy lints expect to find.
The four headings
Each heading is a level-one Markdown heading (# Name) inside a doc comment. Add a section only when it applies.
| Heading | Use it when | What to write |
|---|---|---|
| `# Examples` | Almost always | Runnable code that shows typical use |
| `# Panics` | The function can panic | Each condition that causes a panic |
| `# Errors` | The function returns `Result` | Each condition that returns `Err`, and which variant |
| `# Safety` | The function is `unsafe` | The rules the caller must uphold |
The usual order is a one-line summary, then details, then Examples, Panics, Errors and Safety. Some projects put Panics, Errors and Safety before Examples. Pick one order and use it throughout the crate.
Examples
An example is a fenced code block. rustdoc compiles it and cargo test --doc runs it, so a wrong example fails the build. The examples below use ~~~ fences inside the comments so they fit in this chapter's code blocks. rustdoc treats ~~~ the same as three backticks.
/// Adds two numbers.
///
/// # Examples
///
/// ~~~
/// use mycrate::add;
///
/// assert_eq!(add(2, 3), 5);
/// ~~~
pub fn add(a: i32, b: i32) -> i32 {
a + b
}Panics
List every condition under which the function panics. This lets callers decide whether they need to check inputs first. You can also back the section with a should_panic example, which passes only if the code panics.
/// Divides `n` by `d`.
///
/// # Panics
///
/// Panics if `d` is zero.
///
/// ~~~should_panic
/// mycrate::divide(1, 0);
/// ~~~
pub fn divide(n: u32, d: u32) -> u32 {
n / d
}Errors
For a function that returns Result, name the error type and say when each error occurs. Clippy's missing_errors_doc lint (part of its pedantic group) flags a public function that returns Result without this section.
The example below uses ?. Lines that start with # are compiled but hidden in the rendered page. The last line gives the example block an explicit Result type, which is what lets ? compile.
use std::num::ParseIntError;
/// Parses a decimal port number.
///
/// # Errors
///
/// Returns [`ParseIntError`] if `s` is not a valid `u16`.
///
/// # Examples
///
/// ~~~
/// # use mycrate::parse_port;
/// let port = parse_port("8080")?;
/// assert_eq!(port, 8080);
/// # Ok::<(), std::num::ParseIntError>(())
/// ~~~
pub fn parse_port(s: &str) -> Result<u16, ParseIntError> {
s.trim().parse()
}Safety
An unsafe fn has requirements the compiler cannot check. The Safety section states them as conditions the caller must guarantee. Write it as a contract, not a description of the implementation.
/// Returns the element at `index` without bounds checking.
///
/// # Safety
///
/// `index` must be less than `slice.len()`. Otherwise the call is
/// undefined behavior.
///
/// # Examples
///
/// ~~~
/// let v = [10, 20, 30];
/// let x = unsafe { mycrate::get_unchecked(&v, 1) };
/// assert_eq!(x, 20);
/// ~~~
pub unsafe fn get_unchecked(slice: &[i32], index: usize) -> i32 {
unsafe { *slice.get_unchecked(index) }
}Common mistakes
- Writing
# Errorsas "Returns an error on failure." Name the condition and the variant instead. - Leaving out a panic that comes from indexing or arithmetic overflow in the body.
- Writing
# Safetyon a safe function. Reserve it forunsafeitems. - Putting
# Panicstext on a function whose example never triggers the panic. Add ashould_panicblock so the claim is tested.
Exercise
A public function fn first(v: &[u8]) -> u8 returns v[0]. Which conventional section should its doc comment contain, and what is one way to make that claim checked by cargo test --doc?
Show answer
It needs a # Panics section stating that the function panics if v is empty. To check the claim, add an example fenced with should_panic that calls first(&[]). The doc test passes only if the call panics.