Rust Comments

Comments in Rust let you annotate code for humans; they come in line, block, and documentation forms that the compiler ignores or specially processes.

Line Comments

The most common comment style in Rust starts with two forward slashes, //, and extends to the end of the line. Anything after // on that line is ignored by the compiler entirely.

Line comments

fn main() {
    // This program calculates a discount
    let price = 100;
    let discount = 20; // percentage off
    println!("Discounted price: {}", price - discount);
}

Block Comments

Rust also supports block comments delimited by /* and */, which can span multiple lines. Unlike in C, Rust's block comments can be nested inside one another, which makes it safe to comment out a chunk of code that already contains a block comment.

Block comments

fn main() {
    /* This block explains the constant below.
       It can span as many lines as needed. */
    let max_retries = 3;
    println!("Max retries: {}", max_retries);
}

Documentation Comments

Beyond ordinary comments, Rust has a special third form: documentation comments, written with /// above an item or //! at the top of a module. Tools like cargo doc read these comments and generate browsable HTML API documentation automatically, and they can even contain runnable code examples that cargo test executes as tests.

Documentation comments

/// Adds two numbers together and returns the sum.
///
/// # Examples
///
/// let result = add(2, 3);
/// assert_eq!(result, 5);
fn add(a: i32, b: i32) -> i32 {
    a + b
}

fn main() {
    println!("2 + 3 = {}", add(2, 3));
}
  • // starts a line comment that runs to the end of the line
  • /* ... */ starts a block comment, and Rust allows nesting them
  • /// documents the item immediately below it (a function, struct, or enum)
  • //! documents the enclosing item, typically used at the top of a file or module
  • Comments have zero effect on the compiled binary or its performance
StyleSyntaxTypical Use
Line comment// textQuick, single-line explanations
Block comment/* text */Multi-line notes, temporarily disabling code
Outer doc comment/// textDocumenting the function/struct that follows
Inner doc comment//! textDocumenting the whole module or crate from within it
Note: Run cargo doc --open in any project to generate and view formatted documentation built directly from your /// comments.
Note: Avoid comments that just restate the code, such as '// increment i' above 'i += 1;'. Reserve comments for explaining why, not what.

Exercise: Rust Comments

How do you write a single-line comment in Rust?