Rust Doctests
Rust doctests are code examples written inside documentation comments that the compiler extracts, compiles and runs as real tests, so your documentation's example code is guaranteed to keep working instead of silently rotting out of date.
WHY IT EXISTS Documentation examples rot. A function's signature changes, someone updates the code but forgets the comment above it, and now new users copy paste an example that no longer compiles. Rust doctests exist to make that impossible to ignore: if an example in your docs is wrong, the test suite fails, not just the documentation.
THE MENTAL MODEL Treat every code block in your doc comments as a tiny unit test that happens to double as a tutorial. You are not writing prose that describes code, you are writing code that also happens to explain itself, and the compiler holds you to both jobs at once.
HOW IT WORKS Above an item, a doc comment starts with triple slashes, and a fenced code block inside it, marked with three backticks, is treated as Rust source. When you run cargo test, cargo extracts every such block, wraps it in a hidden main function if one is not already present, compiles it as a standalone binary and executes it. A block passes if it compiles and does not panic. You can write assert_eq to check a return value, use the question mark operator on a function that returns Result to propagate errors, or annotate the block with should_panic if failure is the expected behavior. Lines you want to run but hide from the rendered documentation can be prefixed with a leading hash symbol.
WHEN IT MATTERS Doctests matter most for library crates published to crates.io, where the public API documentation on docs.rs is often a user's first and only experience with your crate before they commit to using it. The footgun is doctest cost: each block compiles as a separate binary, so a crate with hundreds of doctests can noticeably slow down cargo test, which is why some teams mark expensive or environment dependent examples as no_run or ignore.
ONE CONCRETE EXAMPLE A crate defines a function called parse_duration. Its doc comment includes an example showing parse_duration parsing the string 30s and asserting the result equals thirty seconds. If a later refactor changes the function to return a Result instead of a bare Duration, that example fails to compile the moment cargo test runs, catching the breaking documentation change before it ever reaches a release.
Read the original → doc.rust-lang.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.