Sub topic 2
Linking to Other Items with Rust Documentation
Assume you know basic Rust syntax, Cargo library projects, Markdown, and assert_eq!. This chapter shows how to connect API documentation, build it, and keep examples tested.
Linking to Other Items
Rustdoc supports intra-doc links, which are links from one documentation comment to another Rust item. Put the item name in brackets:
/// Parses a port number.
///
/// Returns [`std::num::ParseIntError`] when the input is invalid.
/// See also [`parse_port`].
pub fn parse_port(s: &str) -> Result<u16, std::num::ParseIntError> {
s.trim().parse()
}Rustdoc turns these references into links in the generated HTML. Links make related types and functions easy to discover. Prefer links to repeating long explanations.
Building and Viewing Docs with `cargo doc`
Cargo builds documentation for a crate with cargo doc. The --no-deps option limits the build to your crate, and --open opens the result in a browser:
cargo doc --no-deps --openRustdoc also checks whether intra-doc links resolve. A misspelled link can produce a warning, so treat documentation warnings as errors in continuous integration when practical.
Doc Tests: Examples That Run as Tests
A fenced Rust block inside documentation is normally a doc test. cargo test --doc extracts each example, compiles it as a small program, and runs it:
cargo test --docThe example can use only the crate's public API, just as a user would:
/// Adds two numbers.
///
/// # Examples
///
/// ```
/// use mycrate::add;
///
/// assert_eq!(add(2, 3), 5);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
a + b
}Each example is compiled separately. This catches stale examples when an API changes.
Hiding Setup Lines with `#`
A line beginning with # is compiled but hidden in rendered documentation. Use it for imports, setup, or a final Result value:
/// # Examples
///
/// ```
/// # use mycrate::parse_port;
/// let port = parse_port("8080")?;
/// assert_eq!(port, 8080);
/// # Ok::<(), std::num::ParseIntError>(())
/// ```The learner sees the useful steps, while the hidden lines give the compiler everything it needs.
Exercise
Why might a doc-test example need a hidden Ok::<(), E>(()) line?
Show answer
The line supplies the explicit Result returned by the example, allowing the visible code to use the ? operator.