Comments

Understand single-line comments, multi-line block comments, and documentation comments in Rust, and how to use them effectively.

A comment is text in your source code that the Rust compiler ignores completely. It exists purely for humans—to explain intent, document a tricky algorithm, or leave a note for whoever reads the code next (which might be you, six months later).

Rust offers three comment styles, each with a different purpose:

  • Single-line comments for quick annotations on one line.
  • Multi-line block comments that span several lines—and can even be nested.
  • Documentation comments that the rustdoc tool turns into HTML documentation.

Single-Line Comments

A single-line comment begins with two slashes (//) and runs until the end of that line. Every character after // on the same line is part of the comment and has zero effect on the compiled program.

fn main() {
    // Print a greeting to the terminal.
    let name = "Rust";          // This is also valid.
    println!("Hello, {name}!"); // Comments can appear after code.
}

This style works for short explanations that fit on one line. Use it when the comment is tightly coupled to the line of code right beside it—for example, clarifying a unit conversion or noting why a seemingly obvious expression is intentional.

A common mistake is treating // as a multi-line marker by leaving trailing slashes on the next line. Each line needs its own //.

Every Line Needs Its Own Slashes:

If you want a comment to span multiple lines, you must put // at the start of each line. There is no “everything after this is a comment until I say stop” mechanism with //.

Multi-Line Comments

When a comment is too long for a single line or you need to temporarily disable a whole block of code, use the block comment syntax /* ... */. Everything between /* and the next */ is a comment—even across many lines.

/*
    This function calculates the area of a circle.
    The formula used is π * r², where r is the radius.
    We use f64 for radius because the math crate expects it.
*/
fn circle_area(radius: f64) -> f64 {
    std::f64::consts::PI * radius * radius
}

Block comments can appear anywhere a whitespace is allowed, including in the middle of a line. That can make code hard to read, so it is usually reserved for broad swaths of commented-out code rather than inline remarks.

let result = some_operation(/* unused_param */ 42);

Nested Block Comments

A distinguishing feature of Rust is that block comments nest. If you wrap a section of code that already contains /* ... */ comments with another /* ... */, everything works: the inner */ does not close the outer comment.

/*
    Outer comment wraps a whole module test.
    /*
        Inner comment that explains a specific assertion.
        This is perfectly legal in Rust.
    */
    assert!(1 + 1 == 2);
*/

Languages like C and Java treat the first */ as the end of the outer comment, which can break builds when you try to comment out large sections. Rust's nesting eliminates that risk.

Nesting Is Part of the Language:

Rust’s nested block comments are a deliberate design choice. You never need to worry about accidentally closing an outer comment with an inner */. This makes it safe to comment out entire functions, test modules, or sections of code that already contain block comments.

Documentation Comments

Documentation comments are a special kind of comment that the rustdoc tool extracts to build HTML documentation. They support Markdown formatting and are the primary way Rust libraries communicate usage, examples, and panics to their users.

There are two forms, distinguished by the number of slashes and where they appear:

  • /// documents the item that follows (a function, struct, enum, etc.).
  • //! documents the enclosing item (the module or crate that contains the comment).

Both support Markdown and can include code blocks that rustdoc will test when you run cargo test.

Documenting Items with ///

Place /// directly above a function, struct, enum, constant, or any other item you want to describe.

/// Adds two signed 32‑bit integers and returns the sum.
///
/// # Examples
///
/// ```
/// let result = my_math::add(2, 3);
/// assert_eq!(result, 5);
/// ```
///
/// # Panics
///
/// This function never panics.
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

When you run cargo doc --open, rustdoc generates a page for add with the Markdown rendered, the example formatted as a code block, and the panics section called out. Notice that /// comments must be placed on the line immediately before the item they document—putting a blank line in between can break the attachment.

Blank Lines Break Documentation Attachment:

A blank line between a /// comment and the item it documents severs the association. The comment will be ignored by rustdoc and treated as a regular comment. Always keep them directly adjacent.

Documenting Modules and Crates with //!

When you need to describe the module or crate itself—not a specific function inside it—use //!. These comments appear inside the module’s scope, typically at the top of a file.

//! A collection of simple mathematical utilities.
//!
//! This module provides basic arithmetic operations
//! with a focus on clarity and ease of use.
//!
//! # Example
//!
//! ```
//! use my_math::add;
//! assert_eq!(add(1, 2), 3);
//! ```
pub mod arithmetic {
    /// Adds two numbers together.
    pub fn add(a: i32, b: i32) -> i32 {
        a + b
    }
}

The //! form is called inner documentation because it documents the containing item. You will often see it at the top of lib.rs or main.rs to describe the crate as a whole.

Your Docs Are Alive:

After writing documentation comments, run cargo doc and then cargo test. rustdoc compiles every code block that appears inside /// or //! as a separate test. If your examples are correct, you will see them pass alongside your unit tests—a strong confirmation that your documentation is accurate.

Common Pitfalls

Even though comments seem simple, a few mistakes surface repeatedly.

  • Missing the space after ///. If you write ///without a space, Rust treats it as a regular // comment. The trailing characters are invisible to rustdoc, and your intended documentation disappears. Always add a space: /// With a space.
  • Forgetting to close a block comment. An unclosed /* makes the compiler consume everything after it until it finds a */ or reaches the end of the file—resulting in confusing syntax errors. Rust reports the problematic location, but the error messages can be puzzling if you are not expecting them.
  • Using // for a long explanation and trying to continue on the next line without a new //. Only the first line becomes a comment; the following line is treated as code, which often causes a compile error.
  • Treating doc comments as ordinary comments and omitting examples. Documentation without runnable examples robs users of the quick understanding that a working snippet provides. Include at least one # Examples section with a code block.

Unclosed Block Comments Break Your Build:

An unclosed /* ... */ causes compilation to fail because the compiler never sees the end of the comment. The error might point far from the actual missing delimiter, so check that every /* has a corresponding */.

Summary

Comments bridge the gap between what code does mechanically and why it was written that way. Single-line and block comments document internal reasoning; documentation comments build public-facing guides. Rust’s nested block comments remove a long‑standing frustration from C‑family languages, and its rustdoc integration turns comments into living, testable documentation.