Write doc tests by adding runnable code examples in triple-backtick blocks within Rust documentation comments.
Write doc tests by placing a # before the test code inside a code block in your Markdown documentation. The compiler runs this code to verify the example works as described.
/// Adds two numbers.
///
/// # Examples
///
/// ```
/// let result = add(2, 2);
/// assert_eq!(result, 4);
/// ```
fn add(a: i32, b: i32) -> i32 {
a + b
}
Run the tests with cargo test or mdbook test if using the Rust Book toolchain.
Doc tests are code examples written directly in your documentation comments that the compiler automatically runs to ensure they work. They matter because they keep your examples accurate and your code verified without writing separate test files. Think of them as a self-checking manual that proves every instruction actually does what it says.