Rust Intra-Doc Links
An intra-doc link is a link in a doc comment whose target is a Rust item. The address names the item, not a web page.
A shortcut link
Write the item name in square brackets, with backticks to show it as code:
/// Build one with [`make_box()`].
pub struct MyBox { pub value: i32 }Different words, same target
Put the words first and the item path in round brackets:
/// Read [the box maker](make_box) before this page.When two items share a name
A prefix before @ says which kind of item you mean. The prefix never shows on the page:
/// This is [`struct@Thing`], not [`fn@Thing`].
pub struct Thing { pub x: i32 }Functions and macros wear a mark
A short mark works too — () for a function, ! for a macro:
/// Call [`add_one()`], and fire [`say!`] to print.Example
/// A box that holds one value.
/// Build one with [`make_box()`].
pub struct MyBox { pub value: i32 }
/// Creates a [`MyBox`] that holds `value`.
/// [`MyBox`] links to the struct page, and
/// [`make_box()`] links to this function page.
pub fn make_box(value: i32) -> MyBox { MyBox { value } }
fn main() {
let b = make_box(7);
println!("value = {}", b.value);
}Key points
- An intra-doc link is a doc-comment link whose target is a Rust item in scope, not a web address
- Use a full path when the name alone is not enough: [`std::collections::HashMap`] links across crates
- Link to an associated item by its full path, like [`Widget::new()`], or [`Self::build()`] inside that type's own docs
- Primitives link the same way: [`i32`], [`str`] and [`bool`] resolve to the standard library pages
- A generic name still links: [`Vec<T>`] resolves as if you had written [`Vec`](Vec)
- Links are resolved in the scope of the module where the item is defined.
- That holds even when the item is re-exported somewhere else.
In this example, the two doc comments link to each other. The struct's comment points at [`make_box()`]. The function's comment points back at [`MyBox`]. It also points at itself with [`make_box()`]. The () marks it as the function. On the generated pages, both become real links a reader can click. The program itself is untouched by the links: main builds a box holding 7 and prints value = 7.
Note
A link that cannot be resolved is not an error.
Rustdoc warns (the rustdoc::broken_intra_doc_links lint) and prints the words unlinked — easy to miss until you check the warnings.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
A struct and a function are both named Thing. Which link text points at the struct?