kota's memex

Much like go, rust has a powerful documentation system powered by adding comments above your code definitions. As a result, packages in the Rust ecosystem are extensively documented with clear explanations and working examples. This is in large part due to the ease of creating documentation.

Creating a doc comment has ever so slightly different syntax than a normal code comment by using 3 slashes instead of just 2 along with supporting markdown notation for formatting the text:

/// Adds one to the number given.
///
/// # Examples
///
/// ```
/// let arg = 5;
/// let answer = my_crate::add_one(arg);
///
/// assert_eq!(6, answer);
/// ```
pub fn add_one(x: i32) -> i32 {
    x + 1
}

You can view the documentation of your own crate in a browser with: cargo doc --open

Commonly used sections

There are a number of conventions for the sections you create in your doc comments.

Panics

The scenarios in which the function could panic. Callers of the function who don't want their programs to panic should make sure they don't call the function in these situations.

Errors

If the function returns a Result, describing the kinds of errors that might occur and what conditions might cause those errors to be returned can be helpful to callers so they can handle the different kinds of errors in different ways.

Safety

If the function is unsafe to call, there should be a section explaining why the function is unsafe and covering the invariants that the function expects callers to uphold.

Examples

It's often extremely helpful to show a few examples of the function being used rather than just a textual description. One killer feature is that when you write examples they will actually be tested with cargo test!

Documenting the crate itself

The normal /// doc comments add documentation to the following item, but if you instead want to document the item that contains the comment you need to use a different syntax: //!.

This is usually used at the top of lib.rs to describe the purpose of the crate itself.