Comments and Documenting the code

Comments

// Line comments
/* Block comments */

Nested block comments are supported.

💡 By convention, try to avoid using block comments. Use line comments instead.

Doc Comments

As we discussed, we can generate the project documentation via rustdoc by running the cargo doc command. It uses the doc comments to generate the documentation.

💡 Usually we are adding doc comments on library crates. Also, we can use Markdown notations inside the doc comments.

/// Line comments; document the next item
/** Block comments; document the next item */

//! Line comments; document the enclosing item
/*! Block comments; document the enclosing item !*/

For example,

/// This module contains tests; Outer comment
mod tests {
    
}

mod tests {
    //! This module contains tests; Inner comment

}

💭 The mod keyword is used for modules. Don’t worry about this for now; it’ll be discussed later.

Doc Attributes

Doc attributes are alternatives for doc comments. Especially, we use these doc attributes while we need to set controls on rustdoc. Refer the doc attributes section of rustdoc documentation for more details.

In the following example, each comment is equivalent to relevant doc attribute.

/// Outer comment
#[doc = "Outer comment"]

//! Inner comment
#![doc = "Inner comment"]

🔎 An attribute is a general, free-form metadatum that is interpreted according to the name, convention, language and compiler version. Any item declaration may have an attribute applied to it. Syntax:

  • Outer attribute: #[attr]
  • Inner attribute: #![attr]

👨‍🏫 Before going to the next…

  • Use //! only to write crate-level documentation, nothing else. When using mod blocks, use /// outside of the block. Check the usage of //! and /// doc comments of few popular crates on crates.io. For example, check serde/src/lib.rs and rand/src/lib.rs.

  • Run cargo new hello_lib --lib command to create a sample crate and replace its src/lib.rs file with the following code. Then run cd hello_lib && cargo doc --open to generate the documentation and open it from your web browser.

//! A Simple Hello World Crate

/// This function returns the greeting; Hello, world!
pub fn hello() -> String {
	("Hello, world!").to_string()
}

#[cfg(test)]
mod tests {
    use super::hello;

    #[test]
    fn test_hello() {
        assert_eq!(hello(), "Hello, world!");
    }
}