Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Documentation and Rustdoc Examples

Rule

Document non-obvious public behavior; when a project maintains rustdoc examples, make them compile and use ? for ordinary failures.

Why

Useful rustdoc explains contracts and caveats that names and types cannot express. Obvious restatement and unmaintained examples add noise.

Do

  • Document public invariants, caveats, side effects, and important concepts.
  • Use //! for module-level concepts and /// for item contracts.
  • Add # Errors for caller-relevant failure modes.
  • Add # Panics for public panic behavior and # Safety for unsafe contracts.
  • Add examples only when they materially clarify use and the project opts into maintaining them.
  • Prefer compiling examples with a fallible main and hidden boilerplate.

Avoid

  • Do not require #![deny(missing_docs)] as house style.
  • Do not restate an item’s name or signature in prose.
  • Do not use doctests as default coverage.
  • Do not use bare unwrap in public examples.
  • Do not mark examples ignore merely to avoid maintenance.

Public API Notes

Prioritize constructors, fallible operations, trait contracts, and behavior that callers can misuse. Internal application docs may stay sparse outside shared boundaries.

Example

/// Loads configuration and applies environment overrides.
///
/// # Errors
///
/// Returns an error when the file is unreadable or invalid.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let config = example_config::Config::load("app.toml")?;
/// assert_eq!(config.profile(), "default");
/// # Ok(())
/// # }
/// ```
pub fn load(path: &str) -> Result<Config, ConfigError> {
    Config::read(path)
}

Exceptions

  • Use no_run for examples that compile but would access real services or state.
  • Use ignore only when portability is impossible.
  • Use expect for fixed setup invariants when a fallible wrapper would obscure the API.