Rust Comments

Comments are an essential part of programming. They allow you to explain what your code does, why you wrote it that way, or temporarily disable code without deleting it. Rust supports several types of comments, each useful in different situations.

Single-Line Comments (//) #

The simplest comment is written with //. Everything after // on the same line is ignored by the compiler.

fn main() {
    // This is a single-line comment
    println!("Hello, world!"); // Comments can also be at the end of a line
}
Code language: Rust (rust)

You should use single-line comments for short explanations.

Multi-Line Comments (/* ... */) #

If you need longer explanations, you can use block-style comments:

fn main() {
    /* 
       This is a multi-line comment.
       It can span across multiple lines.
    */
    println!("Hello, Rust!");
}
Code language: Rust (rust)

You can even nest them, unlike in some languages:

fn main() {
    /*
        Outer comment
        /* Nested comment inside */
    */
    println!("Nested comments work!");
}
Code language: Rust (rust)

Documentation Comments (/// and //!) #

Rust has special comments that can generate HTML documentation using the rustdoc tool.

  • /// is used for documenting items like functions, structs, or modules.
  • //! is used for documenting the entire crate or module.

Example:

/// Adds one to the given number.
/// 
/// # Example
/// ```
/// let result = add_one(5);
/// assert_eq!(result, 6);
/// ```
fn add_one(x: i32) -> i32 {
    x + 1
}
Code language: Rust (rust)

To build the documentation:

cargo doc --open

This will open a beautifully formatted documentation page in your browser, including your comments.

Best Practices for Comments #

  • Keep comments short and clear.
  • Explain why you wrote the code, not just what it does.
  • Use /// for public APIs so others can understand how to use your code.
  • Don’t leave outdated comments — they confuse more than they help.

Summary #

  • Use // for quick notes.
  • Use /* ... */ for longer explanations or disabling blocks of code.
  • Use /// and //! for documentation that can be generated with rustdoc.
Was this Helpful ?