Sub topic 3
Controlling Rust Documentation Examples
Assume you know basic Rust, Cargo, Markdown, and library visibility with pub. Rust documentation examples are normally compiled and run as doc tests. Code block attributes change that behavior.
Control How Examples Run
Use an attribute after the opening backticks:
| Attribute | Behavior |
|---|---|
| `no_run` | Compile the example, but do not run it |
| `ignore` | Skip the example entirely |
| `should_panic` | Pass only when the example panics |
| `compile_fail` | Pass only when the example fails to compile |
/// Opens a local listener.
///
/// ```no_run
/// let listener = std::net::TcpListener::bind("127.0.0.1:9000")?;
/// # drop(listener);
/// # Ok::<(), std::io::Error>(())
/// ```
///
/// ```should_panic
/// assert_eq!(2 + 2, 5);
/// ```
///
/// ```compile_fail
/// let number: u32 = "not a number";
/// ```
pub fn examples() {}no_run is useful when execution needs a network, file, or external service. Use ignore when the example cannot be checked automatically, but explain how a reader should run it.
How Doc Tests Work
rustdoc extracts each example and compiles it as a separate test program. The program can use the crate's public API, but it cannot depend on private implementation details. Run these tests with:
cargo test --docThe examples therefore act as small, checked usage guides.
Using `?` in Examples
The ? operator returns an error from the current function. Hide setup lines with #, so they compile but do not appear in rendered documentation.
/// Reads a port number.
///
/// ```
/// # use std::num::ParseIntError;
/// # fn example() -> Result<(), ParseIntError> {
/// let port: u16 = "8080".parse()?;
/// assert_eq!(port, 8080);
/// # Ok(())
/// # }
/// ```
pub fn read_port() {}An explicit Result return type gives ? a valid context.
The `#[doc]` Attribute and Lints
Attributes provide documentation controls that comments cannot. #[doc(hidden)] hides a public item from generated pages. #[doc(alias = "old_name")] makes another search term find an item.
#[doc(alias = "old_name")]
pub fn current_name() {}Require documentation and catch broken links with crate-level lints:
#![warn(missing_docs)]
#![deny(rustdoc::broken_intra_doc_links)]CI and docs.rs
A CI job can keep documentation current:
cargo test --doc
cargo doc --no-depscargo doc --no-deps builds documentation for the current crate. docs.rs builds published crate documentation using Cargo metadata and feature settings. Keep public examples portable, and test feature-specific documentation in CI.
Exercise
Which attribute should you use for code that must compile but should not connect to a real service?
Show answer
Use no_run.