How to Write Doc Tests in Rust

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.