Documentation

Documenting 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(),
    }
}

struct Person {
    name: String,
}

fn main() {
    let _ = new("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.

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.")
}

See also

The rustdoc book

docs.rs⮳: open-source documentation host for Rust crates.