| name | rust-documentation-standards |
| description | Reference knowledge base for the rust-doc-comments agent. Loaded by that agent on its first iteration when the host has not already injected it; not intended for direct invocation. |
Rust Documentation Standards
Comprehensive reference for writing idiomatic Rust documentation.
Core Principles
- Every public item with non-obvious meaning should be documented.
rustdoc generates documentation from /// and //! comments —
undocumented public items produce warnings with #![warn(missing_docs)].
For self-documenting names (new, len, is_empty, Display::fmt-style
String) the right response is to leave them undocumented (or annotate
with #[allow(missing_docs)]), NOT to add a comment that restates the
name — see Mistake 2, which already says
to skip new.
- Write for the user, not the implementer. Focus on what the item does,
what parameters mean, and what errors can occur.
- The first line is the summary. Rustdoc uses the first paragraph as the
short description in module listings and search results. Make it count.
- Complete sentences. Every doc comment must be grammatically correct
with proper punctuation.
Doc Comment Syntax
Item Documentation (///)
/// documents the item that follows it:
pub fn factorial(n: u64) -> Option<u64> {
Module/Crate Documentation (//!)
//! documents the enclosing item (module or crate):
Place //! at the TOP of the file, before any use statements.
Documentation by Declaration Type
Functions
pub fn parse_config(input: &str) -> Result<Config, ConfigError>
Structs
pub struct ClientConfig {
pub timeout: Duration,
pub max_retries: u32,
}
Enums
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum TaskState {
Pending,
Running {
started_at: Instant,
},
Completed {
result: String,
},
Failed {
error: TaskError,
},
}
Traits
pub trait UserRepository: Send + Sync {
fn find_by_id(&self, id: UserId) -> Result<User, RepoError>;
fn save(&self, user: &User) -> Result<(), RepoError>;
}
Constants and Static Items
pub const DEFAULT_TIMEOUT: u64 = 30;
pub const MAX_CONNECTIONS: usize = 100;
Type Aliases
pub type SharedString = Arc<str>;
pub type DbResult<T> = Result<T, DbError>;
Unsafe Functions
Every pub unsafe fn MUST have a # Safety section:
pub unsafe fn read_raw(ptr: *const u8, len: usize) -> Vec<u8>
Special Sections
# Errors
Document every error variant a function can return:
# Panics
Document when a function panics:
# Safety
Document invariants the caller must maintain for unsafe functions:
# Examples
Provide runnable code examples:
Use # prefix for hidden lines (setup/teardown):
Intra-Doc Links
Use square brackets to link to other items:
Link syntax:
[TypeName] — link to a type (preferred short form)
[module::function] — link to a function in another module
[Trait::method] — link to a trait method
[crate::module] — link to a module from anywhere
[Struct.field_name] — link to a struct field (dot notation)
Disambiguation
When a name is ambiguous (e.g., a module and type share a name), use
prefix syntax:
[struct@Foo] — disambiguate to a struct
[fn@bar] — disambiguate to a function
[macro@baz] — disambiguate to a macro
The prefix is stripped in rendered output. Only use disambiguation when
rustdoc emits an ambiguity warning.
Best Practices
- Prefer short-form links.
[Config] over
[crate::config::Config] when the type is in scope.
- Do NOT use full paths when the short form resolves unambiguously.
Doc Test Attributes
| Attribute | Purpose | Use When |
|---|
| (none) | Compile and run | Default — example should work |
no_run | Compile but don't run | Network access, file I/O, long-running |
should_panic | Expect a panic | Demonstrating panic behavior |
compile_fail | Expect compilation failure | Showing what won't compile |
ignore | Skip entirely | Temporarily broken or platform-specific |
Example with no_run:
Enforcing Documentation
Add #![warn(missing_docs)] at the crate root (lib.rs) to produce
compiler warnings for undocumented public items. For stricter enforcement,
use #![deny(missing_docs)].
Common Mistakes
Mistake 1: Fragment Instead of Sentence
Mistake 2: Restating the Name
pub fn new() -> Config
pub fn new() -> Config
Mistake 3: Describing Implementation
Mistake 4: Missing Error Documentation
pub fn load(path: &Path) -> Result<Config, Error>
pub fn load(path: &Path) -> Result<Config, Error>
Mistake 5: Doc Comment Not Adjacent
pub fn useful() {}
pub fn useful() {}
Mistake 6: Using // Instead of ///
pub fn parse(input: &str) {}
pub fn parse(input: &str) {}
Deprecated Items
#[deprecated(since = "0.5.0", note = "use `process_v2` instead")]
pub fn process(data: &[u8]) -> Vec<u8>
Conditional Compilation
Doc comments on conditional items should note the condition:
#[cfg(unix)]
pub mod permissions {
Quality Checklist
Before finishing, verify: