Doc tests
A code block in a /// doc comment is compiled and run by cargo test as a documentation test. The snippet that users copy is the snippet that must work.
Detailed Explanation
Rustdoc treats fenced Rust blocks in docs as tests. /// let x = 1; assert_eq!(x, 1); in a library item will run. The test harness wraps the snippet in a fn main if you did not write one, and it can use the crate by default. That is why the examples in std stay honest.
You hide lines from the rendered docs with # at the start of the line. Those lines still compile. That is how you use helpers without showing them. ```ignore skips the test. ```no_run compiles and does not run (a network example). ```should_panic expects a panic. ```compile_fail expects a compile error, used for type-system illustrations.
Doc tests run only for library crates in the usual setup. They are slower than a tiny unit test because each block is a crate. Keep them short. A three-line "how to construct this type" is the sweet spot. A full program belongs in examples/.
A failing doc test is a failing cargo test. That is the feature. An outdated README example is a documentation bug that CI can catch if the example lives in a /// block or an examples/ binary that CI runs.
When you write a doc test: the public constructor, the one-liner people will paste. When you write ignore: the snippet is illustrative and you cannot make it compile cheaply — prefer no_run if it still should compile. When you skip docs entirely: the item is #[doc(hidden)].
Code Examples
/ Adds two numbers.
/// Adds two numbers.
///
/// pub fn add(a: i32, b: i32) -> i32 {
a + b
}
fn main() {
println!("{}", add(2, 40)); // prints: 42
}Common Gotchas
`ignore` is a lie that rusts
Prefer `no_run` or a real test. `ignore` is how examples rot.
`# ` hides setup
Readers do not see the `use` line. The compiler does. Do not hide the line that is the point of the example.
Each block is a separate crate
State does not persist between two fences. Repeat the setup or write one block.
Doc tests need a library target
A bin-only crate will not run these the way you think. Put the docs on `lib.rs` items.