5.9 Comments in Rust

Comments clarify your code for future readers and maintainers. Rust supports two primary comment styles.

5.9.1 Regular Comments

  1. Single-line:

    #![allow(unused)]
    fn main() {
    // This is a single-line comment
    let x = 5; // Comments can follow code on the same line
    }
  2. Multi-line:

    #![allow(unused)]
    fn main() {
    /*
    This is a multi-line comment. It can span many lines.
    Rust supports nested block comments, allowing you to comment out code that
    already contains comments.
    */
    }

5.9.2 Documentation Comments

Documentation comments are processed by rustdoc to generate HTML docs. They come in two variants:

  • Outer (/// or /** */): Documents the next item (function, struct, etc.).
  • Inner (//! or /*! */): Documents the containing module or crate.
#![allow(unused)]
fn main() {
//! A library for arithmetic operations

/// Adds two numbers.
/// 
/// # Example
///
/// ```
/// let result = add(5, 3);
/// assert_eq!(result, 8);
/// ```
fn add(a: i32, b: i32) -> i32 {
    a + b
}
}

Use /** doc */ or /*! doc */ for multi-line documentation instead of triple slashes if you prefer.

5.9.3 Guidelines

  • Focus on why the code does something rather than what it does, as the code itself typically shows the latter.
  • Use line comments (//) for short remarks, and block comments (/* ... */) for temporarily disabling code or lengthy explanations.
  • Public APIs in libraries should have /// comments with clear usage examples.