Sub topic 9
Controlling examples: no_run, ignore, should_panic, compile_fail
This chapter assumes you can write /// doc comments, put a fenced Rust block under an # Examples heading, and run cargo test --doc. By default every Rust block in a doc comment is compiled and run, and the test passes if it finishes without panicking. Some examples can't meet that rule. They may touch the network, panic on purpose, or show code that must not compile. A short list of attributes after the opening fence covers those cases.
How the attributes work
Attributes go in the info string of the fence, separated by commas. The code samples below use ~~~ fences inside the doc comments. rustdoc accepts tilde fences as well as backtick fences, and they let a doc comment sit inside a backtick-fenced block here.
/// Returns the first element of `items`.
///
/// ~~~should_panic
/// mycrate::first(&[]);
/// ~~~
pub fn first(items: &[i32]) -> i32 {
items[0]
}Each attribute changes what rustdoc checks for that one example:
| Attribute | Compiled? | Run? | Test passes when |
|---|---|---|---|
| (none) | yes | yes | it compiles and does not panic |
| `no_run` | yes | no | it compiles |
| `should_panic` | yes | yes | it compiles and panics |
| `compile_fail` | yes | no | compilation fails |
| `ignore` | no | no | never run, reported as ignored |
| `text` | no | no | not Rust, not tested |
no_run: compile but do not execute
Use no_run when running the code would be slow, destructive, or dependent on the environment. Examples are opening a network socket, reading a file that exists only in production, or waiting for user input. The example still has to compile, so the compiler keeps checking types and signatures.
use std::fs;
use std::io;
/// Reads the configuration file at `path`.
///
/// # Errors
///
/// Returns an error if the file cannot be read.
///
/// # Examples
///
/// ~~~no_run
/// let text = mycrate::read_config("/etc/myapp/config.toml")?;
/// println!("{text}");
/// # Ok::<(), std::io::Error>(())
/// ~~~
pub fn read_config(path: &str) -> io::Result<String> {
fs::read_to_string(path)
}If someone renames read_config or changes its return type, this example fails to build and cargo test --doc reports it. The trailing Ok::<(), std::io::Error>(()) line is hidden with # and makes ? legal in the example.
should_panic: the example must panic
A should_panic example is compiled and run, and the test passes only if the code panics. This is the natural companion to a # Panics section, because the claim "this panics" becomes a check.
/// 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
}Two limits apply:
- rustdoc has no way to check the panic message. Unlike the
#[should_panic(expected = "...")]attribute on unit tests, a doc test passes on any panic. - If the example panics for the wrong reason, such as a typo that triggers
unwraponNonebefore the call you care about, it still passes. Keep these examples to one or two lines.
compile_fail: the example must not compile
Use compile_fail to document what the type system or visibility rules prevent. The test passes only if compilation fails, and the code is never run.
/// A TCP port number that can only be built through [`Port::new`].
pub struct Port(u16);
impl Port {
/// Wraps `n` as a port.
pub fn new(n: u16) -> Port {
Port(n)
}
/// Returns the port number.
pub fn get(&self) -> u16 {
self.0
}
}
/// Because the field is private, code outside the crate
/// cannot build a `Port` directly:
///
/// ~~~compile_fail
/// let p = mycrate::Port(80);
/// ~~~
pub struct _PortNote;The _PortNote item above exists only to give the example somewhere to live in a single listing. In a real crate you would put the example on Port itself.
> A compile_fail example passes for any compile error, including a typo.
ignore: skip the example entirely
ignore tells rustdoc not to compile or run the block. The test report lists it as ignored.
/// Starts the GPU worker.
///
/// ~~~ignore
/// let handle = mycrate::start_gpu_worker();
/// handle.join();
/// ~~~
pub fn start_gpu_worker() {}An ignored example can rot silently. Nothing checks that handle.join() exists. Prefer these alternatives first:
- Use
no_runif the code compiles but cannot run in a test. - Use hidden lines (
#) to supply the setup that makes the example compile. - Use
textif the block is not Rust at all, such as a shell session, a log excerpt, or pseudocode.
ignore can also be restricted by target. ignore-windows skips the example only when the target triple contains windows. This suits platform-specific examples that still run elsewhere.
Combining attributes and other info strings
Attributes combine with commas, in any order:
/// Parses a hex string.
///
/// ~~~should_panic,edition2021
/// mycrate::parse_hex("zz").unwrap();
/// ~~~
pub fn parse_hex(s: &str) -> Result<u32, std::num::ParseIntError> {
u32::from_str_radix(s, 16)
}edition2018, edition2021, and edition2024 pick the language edition for one example. The default comes from your crate's edition.
Any fence whose info string names another language, such as toml, json, console, or text, is treated as non-Rust and left alone. A near-miss such as shoud_panic is not an error by itself. rustdoc treats the block as non-Rust and never tests it. The rustdoc::invalid_codeblock_attributes lint is on by default and warns about these misspellings, so read the warnings in cargo doc output.
What the output looks like
running 5 tests
test src/lib.rs - first (line 3) ... ok
test src/lib.rs - read_config (line 12) - compile ... ok
test src/lib.rs - divide (line 8) - should panic ... ok
test src/lib.rs - Port (line 20) - compile fail ... ok
test src/lib.rs - start_gpu_worker (line 5) ... ignored
test result: ok. 4 passed; 0 failed; 1 ignored; 0 measured; 0 filtered outThe suffixes - compile, - should panic, and - compile fail tell you which mode ran. A growing ignored count in this summary is a sign that examples are going unchecked.
Choosing between them
- Use no attribute for the normal case. A passing example proves the documented behavior.
- Use
no_runwhen side effects or the environment make execution unsafe, but the API usage is real. - Use
should_panicto back up a# Panicssection. - Use
compile_failfor guarantees the compiler enforces, and check the error by hand once. - Use
ignoreas a last resort, and add a comment saying why.
Exercise
An example is marked compile_fail and the test passes. A teammate renames the type it uses, so the code now fails with "cannot find type" instead of the original privacy error. Does the test still pass, and what should you do about it?
Show answer
The test still passes, because compile_fail accepts any compilation error. The example no longer tests what it claims to test. Remove the attribute temporarily, read the actual error, and update the example to use the new name so it fails for the intended reason. Add the error code (for example compile_fail,E0603) as documentation for readers.
Exercise
A function opens a TCP connection to a server that does not exist in the test environment. Which attribute fits its example, and what does it still verify?
Show answer
Use no_run. The example is compiled, so rustdoc still checks that the function exists, takes those arguments, and returns a type compatible with the code that follows. It never executes, so the connection is never attempted.