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. Earlier chapters covered those. Here the focus is the short list of section headings that Rust libraries use to document a function's contract.
Why sections exist
A doc comment can say anything, but readers scan it for the same questions every time. Can this call crash my program? What can it return when it fails? What must I guarantee before calling it? Can I copy a working snippet?
The standard library settled on four headings to answer these questions. The [Rust API Guidelines](https://rust-lang.github.io/api-guidelines/documentation.html) recommend them for public APIs. Each heading is a Markdown level-1 heading written inside the doc comment:
/// Short summary sentence.
///
/// # Panics
///
/// Describes when the function panics.
pub fn example() {}Rustdoc renders these as small subheadings inside the item's documentation. The names are a convention. Rustdoc does not require them, and it does not check them. Tools such as Clippy look for them by name, so use the exact spelling and capitalization.
| Section | Use it when | Reader's question |
|---|---|---|
| `# Examples` | Almost always, for public items | How do I call this? |
| `# Panics` | The function can panic on valid-typed input | Can this crash me? |
| `# Errors` | The function returns `Result` | When do I get `Err`, and which one? |
| `# Safety` | The function is `unsafe` | What must I guarantee? |
Examples
# Examples holds runnable code. Rustdoc compiles every fenced block in it as a doc test, so the section also keeps your documentation correct. The heading may be plural even when you show one example. Std writes # Examples throughout.
A good example does three things:
- It imports the item through the public path, such as
use mycrate::parse_percent;. - It checks results with
assert!orassert_eq!instead of printing them. - It shows normal use first, then edge cases that are worth knowing.
You can place prose between several code blocks. Each block is a separate test.
/// Returns the mean of `values`.
///
/// # Panics
///
/// Panics if `values` is empty.
///
/// # Examples
///
/// ```
/// use mycrate::average;
///
/// assert_eq!(average(&[1.0, 2.0, 3.0]), 2.0);
/// ```
///
/// An empty slice panics instead of returning `NaN`:
///
/// ```should_panic
/// mycrate::average(&[]);
/// ```
pub fn average(values: &[f64]) -> f64 {
assert!(!values.is_empty(), "average of an empty slice");
values.iter().sum::<f64>() / values.len() as f64
}Panics
Use # Panics to list every condition under which the function panics on its own, such as an explicit panic!, assert!, unwrap, expect, indexing, or arithmetic overflow in debug builds. Write each condition as a plain statement: "Panics if values is empty."
Some rules help keep this section useful:
- Document panics caused by the caller's arguments or state. Do not document bugs inside the function, because those should be fixed.
- Skip the section if the function never panics. Do not write "This function does not panic".
- If a function has a non-panicking twin, such as
getand[], mention the twin. - Back the claim with a
should_panicexample, asaveragedoes above. The doc test then fails if the code stops panicking.
A should_panic doc test passes if the code panics at all. It does not check the message. A panic from a typo in your example, such as a missing import, would not make the test pass, because that is a compile error and compile errors still fail the test.
Errors
For a function that returns Result, # Errors explains when Err is returned and what it contains. If there is more than one error variant, name each one and its cause. Link to the error type with an intra-doc link, which the next chapter covers in more detail.
/// Why a percentage failed to parse.
#[derive(Debug, PartialEq, Eq)]
pub enum PercentError {
/// The text was not a non-negative whole number.
Invalid,
/// The number was greater than 100.
OutOfRange,
}
/// Parses a whole-number percentage between 0 and 100.
///
/// Leading and trailing whitespace is ignored.
///
/// # Errors
///
/// Returns [`PercentError::Invalid`] if `s` is not a non-negative
/// whole number, and [`PercentError::OutOfRange`] if it is above 100.
///
/// # Examples
///
/// ```
/// use mycrate::{parse_percent, PercentError};
///
/// assert_eq!(parse_percent(" 42 "), Ok(42));
/// assert_eq!(parse_percent("abc"), Err(PercentError::Invalid));
/// assert_eq!(parse_percent("101"), Err(PercentError::OutOfRange));
/// ```
pub fn parse_percent(s: &str) -> Result<u8, PercentError> {
let n: u32 = s.trim().parse().map_err(|_| PercentError::Invalid)?;
if n > 100 {
Err(PercentError::OutOfRange)
} else {
Ok(n as u8)
}
}Notice that the examples test the error paths. A reader learns what Err looks like, and the compiler checks that the variants you named still exist.
A function that returns Result can also panic. In that case, give it both sections. An Err is for expected failures that the caller can handle. A panic marks misuse of the API.
Safety
An unsafe fn cannot be checked by the compiler, so its caller takes on obligations. # Safety states those obligations exactly. Write them as conditions the caller can verify: valid pointers, lengths, alignment, aliasing, initialization, and thread-safety. Say that breaking them is undefined behavior if that is the consequence.
/// Reads the byte at `index` without bounds checking.
///
/// # Safety
///
/// The caller must ensure that `index < slice.len()`. Calling this
/// with an out-of-bounds index is undefined behavior.
///
/// # Examples
///
/// ```
/// let data = [10u8, 20, 30];
///
/// // SAFETY: 1 is less than data.len(), which is 3.
/// let byte = unsafe { mycrate::get_byte_unchecked(&data, 1) };
/// assert_eq!(byte, 20);
/// ```
pub unsafe fn get_byte_unchecked(slice: &[u8], index: usize) -> u8 {
// SAFETY: the caller guarantees `index < slice.len()`.
unsafe { *slice.get_unchecked(index) }
}There are two kinds of safety comments, and they are easy to mix up:
# Safetyin a doc comment goes on the declaration of anunsafe fnorunsafe trait. It tells callers what they must do.// SAFETY:in a regular comment goes at eachunsafeblock. It explains why the obligations hold at that spot.
A safe function that uses unsafe internally does not need a # Safety section. If its safety depends on an internal invariant, document the invariant in a normal comment for maintainers.
Other headings you will see
Std also uses # Aborts for functions that can abort the process, and # Undefined Behavior for cases that need extra emphasis. Add them only when they apply. Do not make up headings for general prose. Use ordinary paragraphs or ## subheadings for that, such as ## Performance.
Section order
Std puts the one-line summary first, then more detailed explanation, then # Panics, # Errors, # Safety, and finally # Examples. In practice, the order varies. Pick one order for your crate and apply it consistently. A reader who knows where to look will find things faster than one who has to scan.
Checking that sections are present
Clippy has lints that look for missing sections:
| Lint | Default level | What it flags |
|---|---|---|
| `clippy::missing_safety_doc` | warn | A public `unsafe fn` without `# Safety` |
| `clippy::missing_errors_doc` | allow (pedantic) | A public function returning `Result` without `# Errors` |
| `clippy::missing_panics_doc` | allow (pedantic) | A public function whose body can panic, without `# Panics` |
| `clippy::undocumented_unsafe_blocks` | allow (restriction) | An `unsafe` block without a `// SAFETY:` comment |
The pedantic and restriction lints are off until you enable them. To enable them for a crate, add this at the top of lib.rs:
#![warn(clippy::missing_errors_doc, clippy::missing_panics_doc)]
#![warn(clippy::undocumented_unsafe_blocks)]Then run:
cargo clippy --all-targetsmissing_panics_doc looks at panicking calls written directly in the function body. It does not follow calls into other functions. A function that calls average and passes along an empty slice will not be flagged, so you still have to read the code yourself.
Common mistakes
- Wrong spelling or level.
# Panic,# Error, or## Panicsis a valid heading, but Clippy and readers will not recognize it as the conventional section. Use# Panics,# Errors,# Safety. - Vague contracts. "Panics if the input is bad" tells the reader nothing. State the exact condition.
- Sections that drift from the code. If the function stops panicking on empty input, the
should_panictest fails and shows you. An untested prose claim does not. - Examples that only show success. An
# Errorssection with only anOkexample hides the part the reader is looking for. - Calling an unsafe function in an example without a
// SAFETY:comment. Examples are copied. Show the habit you want readers to copy.
Exercise
A public function pub fn first_word(s: &str) -> &str calls s.split_whitespace().next().expect("no words"). Which conventional sections does it need, and how do you test the claim in the documentation?
Show answer
It needs # Panics (it panics when s has no words, such as an empty or all-whitespace string) and # Examples. It has no Result return and is not unsafe, so it needs no # Errors or # Safety. Add a normal example with assert_eq!(first_word("hello world"), "hello"); and a second block fenced as should_panic that calls first_word(" "), so the doc test fails if the panic ever disappears.
Exercise
What is the difference between a # Safety section and a // SAFETY: comment?
Show answer
# Safety is part of the doc comment on an unsafe fn or unsafe trait and lists what the caller must guarantee. // SAFETY: is a regular comment placed at an unsafe block and explains why those guarantees hold at that call site.