Documentation

TopicRust Crates
Documentation Generatorcargo doc (built-in)
Doc CommentsUse /// or //! in your code.
Testing with Documentation ExamplesUse #[doc = "```"] in doc comments
Markdown Processing (for docs)pulldown-cmark, comrak
Generating Documentation from TestsOften done with custom scripts or build tools.
API Documentation Generators (for REST APIs, etc.)Often tied to web frameworks; no single dominant crate.

Document Your Code

  • Add documentation comments to your code.
/// This is a doc comment
/// Note the three slashes
/// The first line is equivalent to the next line.
/// This is a doc comment
fn documented_function() {
    println!("Function with doc comment.");
}

// Alternatively, you may use an external file

#[doc = include_str!("../../../../README.md")]
fn function_including_external_file_as_documentation() {}

fn main() {
    documented_function();
    function_including_external_file_as_documentation();
}

rustdoc⮳ uses the CommonMark Markdown specification.

#![allow(dead_code)]

/// Returns a person with the name given them
///
/// # Arguments
///
/// * `name` - A string slice that holds the name of the person
///
/// # Examples
///
/// ```
/// // You can have rust code between fences inside the comments
/// // If you pass --test to `rustdoc`, it will even test it for you!
/// use doc::Person;
/// let person = Person::new("name");
/// ```
fn new(name: &str) -> Person {
    Person {
        name: name.to_string(),
    }
}

#[derive(Debug)]
struct Person {
    name: String,
}

fn main() {
    let john = new("John");
    println!("{:?}", john);
}

Any item annotated with #[doc(hidden)] will not appear in the documentation.

Run rustdoc src/lib.rs --crate-name <name> or cargo doc --open to create a new directory, doc (or target/doc when using cargo), with a website inside.

Create Module- or Crate-level Documentation

Use //! at the top of the file (instead of ///) for module-level documentation.

The first lines within lib.rs will compose the crate-level documentation front-page.

//! Fast and easy queue abstraction.
//!
//! Provides an abstraction over a queue. When the abstraction is used
//! there are these advantages:
//! - Fast
//! - `[Easy]`
//!
//! [Easy]: http://thatwaseasy.example.com

fn main() {
    println!(
        "//! ... are `inner` comments that apply to the containing module (or crate)."
    );
}

To add a "run" button on your documentation (allowing its execution in the rust playground), use the following attribute:

#![doc(html_playground_url = "https://playground.example.com/")]

fn main() {
    println!("Note the above is an _inner_ attribute that starts with #!");
    println!("It should be place at the top of your crate.")
}

Add Documentation to Function Arguments in Rust

roxygen roxygen-crates.io roxygen-github roxygen-lib.rs cat-development-tools cat-rust-patterns

roxygen helps seamlessly document function parameters with rustdoc.

References