Overview
rustdoc renders /// doc comments (Markdown) into the API documentation every Rust
developer lives in, and — its defining trick — compiles and runs every code block in
them as a test. docs.rs then builds and hosts documentation for every release of every
crates.io crate automatically, no publishing step, which is why Rust documentation has
a uniform look and a reliable home the way pkg.go.dev
gives Go, with the doctest guarantee on top: examples in Rust docs are never stale.
Key points
- Doctests are tests: every
```rustblock in a doc comment runs undercargo test; hidden setup lines (# let pool = …;) keep examples readable while still compiling. This is the single highest-leverage documentation feature in the ecosystem. - Intra-doc links:
[`HashMap`]and[Self::insert]resolve by path at build time and break loudly when the item moves — no rotting URLs between items. //!documents the enclosing item (crate/module front page);///documents the next item. Crate-level docs with a quick-start example are the ecosystem norm.cargo doc --openbuilds docs for your crate and all dependencies locally — offline-complete API reference for the whole dependency graph.- docs.rs builds every release: nightly toolchain, all features definable via
[package.metadata.docs.rs](all-features = trueis common), and#[doc(cfg(feature = "tls"))]renders which feature gates each item — check the little version/feature banner when reading. #[doc(hidden)]hides public-for-macro items;--document-private-itemsflips the view for internal-docs use.cargo docwarnings are CI-gateable:RUSTDOCFLAGS="-D warnings"catches broken intra-doc links before they ship.- Examples directory as extended docs:
examples/*.rsare compiled by CI (cargo build --examples) and linked from docs — the convention for anything too big for a doctest.
Examples
/// Parses a duration like `"1h30m"`.
///
/// ```
/// # use mycrate::parse_duration;
/// assert_eq!(parse_duration("90m")?.as_secs(), 5400);
/// # Ok::<(), mycrate::ParseError>(())
/// ```
///
/// See also [`Duration`](std::time::Duration).
pub fn parse_duration(s: &str) -> Result<Duration, ParseError> { /* … */ }
Related
- The Rust toolchain — parent catalog.
- Unit testing — where doctests sit in the test portfolio.
- Cargo in depth — the metadata section docs.rs reads.
- go doc & pkg.go.dev — the Go counterpart;
same shared-reference role, without executable examples in docs (Go's live in
_test.gofiles instead). - javadoc — the JVM ancestor of the genre.