Sub topic 12
The #[doc] attribute: hidden, alias, and more
This chapter assumes you can already write /// and //! comments and run cargo doc and cargo test --doc. It also assumes you know how pub visibility and re-exports (pub use) work. Here you will see what those comments really are, and how the #[doc] attribute controls what rustdoc shows, how users find items, and how doc tests are configured.
Doc comments are attributes
A /// comment is syntax sugar. The compiler rewrites each line into a #[doc = "..."] attribute. A //! comment becomes #![doc = "..."], with the ! marking an attribute that applies to the enclosing item.
These two functions have identical documentation:
/// Adds two numbers.
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
#[doc = "Subtracts `b` from `a`."]
pub fn sub(a: i32, b: i32) -> i32 {
a - b
}The = "..." form accepts more than a string literal. It also accepts macros that expand to a string, such as concat!, env!, and include_str!. This is useful for generated or shared text:
#[doc = concat!("This crate is version ", env!("CARGO_PKG_VERSION"), ".")]
pub fn version() -> &'static str {
env!("CARGO_PKG_VERSION")
}The #[doc(...)] form with parentheses is different. It does not add text. It passes an instruction to rustdoc. The rest of the chapter covers these instructions.
Reusing a README with include_str!
Many crates keep a README.md that duplicates the crate-level docs. You can include the file instead of copying it:
#![doc = include_str!("../README.md")]Put this at the top of lib.rs. The path is relative to the file containing the attribute. Rust code blocks in the README become doc tests, so a stale README example fails cargo test --doc. Keep in mind that README-only conventions, such as badges, will also appear in the rendered crate page.
Hiding items with #[doc(hidden)]
#[doc(hidden)] removes an item from the rendered HTML and from the search index.
#[doc(hidden)]
pub fn __format_name(name: &str) -> String {
format!("<{name}>")
}
/// Wraps a name in angle brackets.
///
/// ```
/// assert_eq!(mycrate::tag!("p"), "<p>");
/// ```
#[macro_export]
macro_rules! tag {
($name:expr) => {
$crate::__format_name($name)
};
}The usual reason for this pattern is macros. A macro_rules! macro expands in the caller's crate, so any helper it calls must be pub. Hiding the helper keeps it out of the documentation while leaving it callable. The leading double underscore is a naming convention that tells readers the item is not meant for direct use.
You can also hide trait methods, enum variants, struct fields, and whole modules.
Making items findable with #[doc(alias)]
Rustdoc's search matches item names. Users often search with a name from another language or library. #[doc(alias = "...")] adds extra search terms for an item.
pub struct Buffer {
data: Vec<u8>,
}
impl Buffer {
pub fn new() -> Self {
Buffer { data: Vec::new() }
}
#[doc(alias = "push")]
#[doc(alias = "append")]
pub fn write_byte(&mut self, b: u8) {
self.data.push(b);
}
}Searching for push in the generated docs now finds Buffer::write_byte. A list form is equivalent: #[doc(alias("push", "append"))].
Aliases only affect search. They do not create a symbol, and they do not appear as text on the item's page. Rustdoc rejects empty aliases, aliases containing quote characters, and aliases that start or end with a space. Use aliases for names people really type, such as malloc for an allocation function or strlen for a length method. Do not use them for keyword stuffing.
Controlling re-exports
A pub use re-export can be shown in two ways. Rustdoc can show a line such as pub use crate::parser::Parser; on the page and link to the original. Or it can inline the item, which copies the full documentation onto the page where the re-export lives.
By default, rustdoc inlines a re-export when the original is not otherwise reachable, for example because it lives in a private module. It does not inline in other cases. You can override the choice:
mod parser {
/// Parses text into tokens.
pub struct Parser;
}
pub use crate::parser::Parser;
#[doc(no_inline)]
pub use std::io::Error as IoError;
#[doc(inline)]
pub use std::collections::HashMap;#[doc(inline)]forces the full documentation to appear at the re-export, even when the source item is public in another place.#[doc(no_inline)]shows only a re-export line with a link. Use it when you re-export a foreign type for convenience and do not want to duplicate its documentation.
Inlining Parser above matters. Without it, users would see a documented type that lives in a private module and has no page of its own.
Configuring doc tests with #![doc(test(...))]
Crate-level doc(test(...)) options change how every doc test in the crate is compiled. The most useful one is attr, which adds a crate attribute to each test program:
#![doc(test(attr(deny(warnings))))]Put this at the top of lib.rs. A doc test that now produces any compiler warning, such as an unused variable, fails. This keeps examples tidy. Another option, no_crate_inject, stops rustdoc from automatically adding extern crate mycrate; to each test. Most crates do not need it.
Showing feature requirements with doc(cfg)
When an item exists only with a Cargo feature, readers of the docs want to see that. The doc(cfg) attribute prints a badge such as "Available on crate feature json only." It is a nightly feature, but docs.rs builds with nightly, so you can enable it only under a custom cfg:
#![cfg_attr(docsrs, feature(doc_cfg))]
#[cfg(feature = "json")]
#[cfg_attr(docsrs, doc(cfg(feature = "json")))]
pub fn to_json(value: &str) -> String {
format!("\"{value}\"")
}Then tell docs.rs to set the docsrs cfg in Cargo.toml:
[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]
[lints.rust]
unexpected_cfgs = { level = "warn", check-cfg = ['cfg(docsrs)'] }The [lints.rust] entry tells the compiler that docsrs is an expected cfg name. Without it, recent compilers warn about an unknown cfg. Because this machinery is nightly-only, the exact feature names have changed between nightly releases. Check the current rustdoc book before copying this into a real project.
On stable, building with cargo doc simply ignores the docsrs branch, so your crate still builds.
Summary of common #[doc] options
| Attribute | Applies to | Effect |
|---|---|---|
| `#[doc = "text"]` | Any item | Same as a `///` line |
| `#![doc = include_str!("...")]` | Crate or module | Uses a file as documentation |
| `#[doc(hidden)]` | Items, fields, variants | Removes from HTML and search |
| `#[doc(alias = "name")]` | Items | Adds a search term |
| `#[doc(inline)]` | `pub use` | Copies docs to the re-export |
| `#[doc(no_inline)]` | `pub use` | Shows only a link |
| `#![doc(test(attr(...)))]` | Crate | Adds attributes to every doc test |
| `#[doc(cfg(...))]` | Items (nightly) | Shows a feature badge |
Common mistakes
- Treating
hiddenas private. Hidden items remain part of your public API surface. - Hiding an item that is mentioned in an intra-doc link. The link will fail or point nowhere. Run
cargo docand read the warnings. - Using
#![doc = include_str!(...)]with a path relative to the wrong file. The path is relative to the source file that contains the attribute, not to the crate root. - Putting
#![cfg_attr(docsrs, feature(doc_cfg))]on a stable toolchain without thedocsrscfg. This is fine, because thecfg_attrstays inactive. Problems only appear if you enable the cfg on stable. - Adding many aliases. Search results fill with noise and the useful ones are harder to find.
Exercise
A crate exports a macro log_line! that expands to a call to $crate::__emit(...). The function __emit must be pub. How do you keep __emit out of the generated docs, and does that stop users from calling it?
Show answer
Add #[doc(hidden)] to __emit. This removes it from the HTML pages and the search index. It does not stop users from calling it, because the function is still pub. It also still counts as part of the crate's reachable API, so changing it can break code that calls it directly.
Exercise
You want every doc test in your crate to fail if it produces a compiler warning. Which line do you add, and where?
Show answer
Add #![doc(test(attr(deny(warnings))))] at the top of lib.rs. The attr option adds #![deny(warnings)] to each doc test program, so any warning becomes a compile error and the test fails.
Exercise
A method named write_byte should be found when someone searches for push in the docs. Which attribute do you use, and does the word push appear on the method's page?
Show answer
Use #[doc(alias = "push")] on the method. The alias only affects search, so searching for push finds write_byte, but the word push does not appear as text on its page.