Sub topic 5
Linking to other items
Good documentation points readers to related types and functions. Rust does this with intra-doc links: you write an item's Rust path inside a Markdown link, and rustdoc turns it into a working hyperlink. This chapter assumes you can write /// and //! comments, you know basic Markdown, and you know how use and module paths work. It also assumes you know what pub visibility means.
Why use paths instead of URLs
You could link to another page with a relative HTML path such as ../struct.PortError.html. That breaks when the item moves, when you re-export it, or when the documentation is hosted somewhere else. An intra-doc link uses the path you would write in code, and rustdoc finds the real page at build time. If you rename the item, the build warns you instead of silently publishing a dead link.
Basic link forms
Put a path in square brackets. Adding backticks inside the brackets renders the link in code style, which is the usual choice for item names.
/// Returns the port as a number, or a [`PortError`] if it is invalid.
pub fn describe() {}These are the forms you will use most.
| Form | Example | Result |
|---|---|---|
| Shortcut | ``[`PortError`]`` | Link text is the path as written |
| Custom text | ``[the error type](PortError)`` | Link text is your own words |
| Reference style | ``[`PortError`]: crate::PortError`` | Defines a target once and reuses it |
| Heading on the same page | `[see below](#errors)` | Jumps to a heading in the current page |
Paths follow normal Rust rules. You can use crate::, self::, and super::. You can also use the name of a dependency, so `[std::collections::HashMap] works without any import. Generic arguments are allowed and are ignored, so [Vec<T>] links to Vec`.
Scope: names resolve where you write them
A link resolves in the scope of the item that carries the comment, as if you had written the path in the code next to it. If PortError is defined or imported in that module, `[PortError] works. If it lives elsewhere and is not imported, use a full path such as [crate::errors::PortError]`.
For //! comments, the scope is the module itself. For a /// comment on an item, the scope is the module that contains the item. For a method inside an impl block, Self is available.
A complete example
This lib.rs uses several kinds of links. It compiles as shown, and it contains no code blocks in the comments, so cargo test --doc has nothing extra to run.
//! Port parsing utilities.
//!
//! Call [`parse_port`] to turn text into a port number. Failures are
//! described by [`PortError`]. The bounds live in the [`limits`] module.
use std::fmt;
pub mod limits {
//! Bounds used by [`parse_port`](crate::parse_port).
/// Lowest port accepted by [`parse_port`](crate::parse_port).
pub const MIN_PORT: u16 = 1;
}
/// The reason [`parse_port`] rejected its input.
///
/// This type implements [`fmt::Display`], so it can be printed directly.
/// Use [`PortError::Empty`] when nothing was supplied.
#[derive(Debug, PartialEq)]
pub enum PortError {
/// The input contained no characters after trimming.
Empty,
/// The input was not a number in the range allowed by [`limits::MIN_PORT`]
/// and `u16::MAX`.
Invalid,
}
impl fmt::Display for PortError {
/// Writes a short message. See [`Self::Empty`] and [`Self::Invalid`].
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PortError::Empty => write!(f, "port is empty"),
PortError::Invalid => write!(f, "port is invalid"),
}
}
}
/// Parses a decimal port number.
///
/// # Errors
///
/// Returns [`PortError::Empty`] for blank input and [`PortError::Invalid`]
/// for anything that does not parse as a [`u16`] of at least
/// [`limits::MIN_PORT`].
pub fn parse_port(s: &str) -> Result<u16, PortError> {
let s = s.trim();
if s.is_empty() {
return Err(PortError::Empty);
}
match s.parse::<u16>() {
Ok(p) if p >= limits::MIN_PORT => Ok(p),
_ => Err(PortError::Invalid),
}
}Several things are worth noting here:
- `
[PortError::Empty]` links to an enum variant, using the same path you would write in code. - `
[fmt::Display]works becauseuse std::fmt;` is in scope for that module. - `
[Self::Empty]works inside theimplblock, whereSelfisPortError`. - `
[u16]` links to the primitive type's page in the standard library documentation. - The custom-text form `
[parseport`](crate::parseport)`is needed insidelimits, becauseparse_port` is not in scope there.
How rustdoc resolves a link
When rustdoc finds [text] in a doc comment, it checks whether the text could be a path. It then tries to resolve it as a Rust name in the scope described above. If one item matches, it emits a link. If nothing matches, it warns. If several items match, it warns about ambiguity.
Ambiguity and disambiguators
Rust keeps names in separate namespaces. A module and a function can both be called parse, because modules live in the type namespace and functions live in the value namespace. A link to [parse] then has two possible targets.
Tell rustdoc which one you mean with a prefix or suffix:
pub mod parse {
//! Low-level parsing helpers.
}
/// Parses input using the helpers in [`mod@parse`].
///
/// Not to be confused with the function itself, written ``[`parse()`]``.
pub fn parse() {}The common disambiguators are:
- Prefixes:
struct@,enum@,trait@,union@,mod@,fn@,const@,static@,type@,value@,macro@,derive@,variant@,field@,prim@. - Suffix for functions and methods:
name(). - Suffix for macros:
name!, orname!()and similar forms.
For example, `[vec!] links to the macro, and [fn@parse]` forces the function.
Links to methods and trait items
Associated items use the path of their parent type: `[Vec::push] or [PortError::fmt]. If a type has an inherent method and a trait method with the same name, the inherent one is chosen unless you qualify it. To link to a trait's method, name the trait: [fmt::Display::fmt]`.
Private items and visibility
Rustdoc can resolve a link to a private item, but the target page may not exist in the output. Linking from public documentation to a private item triggers the rustdoc::private_intra_doc_links warning. Two fixes are common. You can make the item public, or you can describe it in plain words without a link. Linking from private docs to private items is fine when you build with cargo doc --document-private-items.
Imports used only for links
Sometimes the target is not in scope and a long path would clutter the text. You can import it just for the docs. A plain use would trigger an unused import warning in normal builds, so guard it with cfg(doc):
#[cfg(doc)]
use std::collections::BTreeMap;
/// Stores entries in sorted order, like a [`BTreeMap`].
pub struct SortedStore;The import exists only while rustdoc runs, so it has no effect on the compiled library.
Warnings and how to enforce them
Broken links produce a warning from the rustdoc::broken_intra_doc_links lint. A warning is easy to miss, so many projects turn warnings into failures. Two ways to do that are:
RUSTDOCFLAGS="-D warnings" cargo doc --no-depsor, in lib.rs:
#![deny(rustdoc::broken_intra_doc_links)]Other relevant lints are rustdoc::private_intra_doc_links and rustdoc::redundant_explicit_links. The second warns when you wrote both a custom path and a shortcut that already points to the same item.
Edge cases
- Links inside fenced code blocks and inline code spans are not resolved. Brackets in `
a[0]stay as text. The shortcut[Name]` works because the backticks sit inside the brackets, not around them. - Text such as
[0]or[x]in prose can be mistaken for a link. If rustdoc reports a broken link for it, escape it as\[0\], or put it in a code span. - Links resolve in the scope of the source item, not of the page where the docs appear. Re-exports show the original docs, so write paths that work at the definition site.
- Links to dependencies need the dependency to be documented too. With
--no-deps, those links point to the online documentation instead.
Check your understanding
Exercise
Inside a method in impl PortError, you want to link to the variant Invalid of the same enum. Which link text works without importing anything, and why?
Show answer
`[Self::Invalid] works. Inside an impl block, Self` refers to the type being implemented, and rustdoc resolves the variant through it, exactly as the compiler would in code.
Exercise
A crate has pub mod config and pub fn config(). Rustdoc warns that `[config]` is ambiguous. Write one link to each target.
Show answer
Use `[mod@config] for the module and [config()] (or [fn@config]`) for the function. The prefix or the parentheses select the namespace.
Exercise
Your public function's docs link to a private helper, and cargo doc prints a warning from rustdoc::private_intra_doc_links. Name two ways to resolve it.
Show answer
Make the helper public so that its page exists, or remove the link and describe the helper in plain text. Alternatively, build with --document-private-items if the docs are meant for internal readers.