Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Rust Dictionary

  1. Home
  2. Rust Dictionary
  3. Comments (// /// //! and /* */ /** */ /*! */)

Comments (// /// //! and /* */ /** */ /*! */)

Rust has six types of comments. In addition to regular code comments (// and /* */), Rust provides documentation comments: /// (line doc comment), //! (crate/module doc comment), /** */ (block line doc comment), and /*! */ (block module doc comment). Documentation comments support Markdown syntax, and the standard tool cargo doc generates HTML documentation from them automatically.

Syntax

// Single-line comment — everything from // to the end of the line is a comment.
let x = 10; // Inline comment — can also be written after code.

/* Block comment — everything between /* and */ is a comment.
   Unlike C, Rust block comments can be nested. */

/* outer /* inner */ outer continues — this is valid in Rust */

/// Line doc comment — documents the item immediately following it
/// (function, struct, enum, module, etc.). Supports Markdown.
fn example_function() {}

//! Crate/module doc comment — documents the module or crate the comment belongs to.
//! Write at the top of a file or at the top of a mod block.

/** Block line doc comment.
 * Same as ///, but written as a block. Useful for multi-line docs.
 */
fn block_doc_function() {}

/*! Block module doc comment.
 * Same as //!, but written as a block.
 */

Comment Types

TypeSyntaxDescription
Single-line comment// textEverything from // to the end of the line becomes a comment. The most frequently used comment type.
Block comment/* text */Used when writing a comment that spans multiple lines. Unlike C, Rust block comments can be nested.
Line doc comment/// textDocuments the item immediately following it (function, struct, enum, module, etc.). Supports Markdown syntax.
Crate/module doc comment//! textDocuments the enclosing item (crate or module). Written at the top of a file or the top of a mod block.
Block line doc comment/** text */The block version of ///. Allows writing multiple lines in a single block.
Block module doc comment/*! text */The block version of //!. Allows writing the module or crate description in a single block.

Documentation Comments and cargo doc

Documentation comments written with /// and //! are processed by cargo doc, the standard Rust tool, to generate HTML documentation. The output is placed in target/doc/ and can be viewed in a browser.

cargo doc
cargo doc --open

Documentation comments support Markdown syntax. Code blocks (wrapped in triple backticks) also function as doc tests and can be executed with cargo test.

ConventionDescription
```rust ... ```Code block. Executed as a doc test by cargo test.
# ExamplesSection for usage examples. The heading "Examples" is the conventional name.
# PanicsDocuments conditions under which the function panics.
# ErrorsDocuments conditions under which Result::Err is returned.
# SafetyDocuments the safety conditions required when calling an unsafe function.

When to Write Comments and When Not To

DecisionSituationReason
Write a commentThe reason why something was implemented a certain wayDesign decisions and trade-offs that cannot be understood from the code alone help your future self and other developers.
Write a commentComplex algorithms or formulasAdd a brief description of what a piece of logic does when its behavior is not immediately obvious at a glance.
Write a commentPublic API functions, structs, and traitsAdding /// doc comments allows cargo doc to generate HTML documentation, which also appears automatically on crates.io.
Write a commentSafety conditions for unsafe blocksDocumenting why the code is safe helps future maintainers verify correctness after changes.
No comment neededLogic that is obvious from reading the codeSelf-evident explanations become noise. Clear variable and function names remove the need for such comments.
No comment neededChange history or deleted codeBecause version control (git) is available, there is no need to keep old code or change dates in comments.

Sample Code

comment_basic.rs
// comment_basic.rs — Basic usage of Rust comment syntax.

fn main() {
    // Define arrays of item names and prices
    let items = ["widget", "gadget", "device"];
    let prices = [1200_i32, 3500, 800]; // Underscores can be used as digit separators

    /* Calculate the total and print the result */
    let total: i32 = prices.iter().sum();

    for (item, price) in items.iter().zip(prices.iter()) {
        println!("{:<10} {:>5} yen", item, price);
    }

    println!("----------");
    println!("{:<10} {:>5} yen", "Total", total);
}

Running the above produces the following output:

$ cargo run
widget      1200 yen
gadget      3500 yen
device       800 yen
----------
Total       5500 yen
comment_doc.rs
//! This module provides statistical calculations for integer arrays.
//! Running `cargo doc` displays this comment as the crate overview.

/// Computes the average of an integer slice and returns it.
///
/// Returns `None` if the slice is empty.
///
/// # Examples
///
/// ```
/// let scores = vec![85, 92, 78, 95, 60];
/// assert_eq!(calculate_average(&scores), Some(82.0));
/// ```
///
/// # Errors
///
/// Returns `None` when the slice is empty (does not panic).
pub fn calculate_average(values: &[i32]) -> Option<f64> {
    if values.is_empty() {
        // Empty slice cannot be averaged — return None
        return None;
    }

    let sum: i32 = values.iter().sum();

    /* Cast to perform floating-point division */
    Some(sum as f64 / values.len() as f64)
}

fn main() {
    let scores = vec![85, 92, 78, 95, 60];

    match calculate_average(&scores) {
        Some(avg) => println!("Average: {:.1}", avg),
        None => println!("No data"),
    }

    // Empty slice case
    let empty: Vec<i32> = vec![];
    println!("Empty: {:?}", calculate_average(&empty));
}

Running the above produces the following output:

$ cargo run
Average: 82.0
Empty: None
comment_nested_block.rs
// comment_nested_block.rs — Block comments can be nested in Rust.

fn main() {
    /* outer comment
       /* inner comment */
       outer continues — this is valid in Rust (unlike C/C++).
    */

    let value = 42;
    println!("value: {}", value);
}

Running the above produces the following output:

$ cargo run
value: 42

Overview

Rust comments fall into two groups: regular comments (// and /* */) and documentation comments (///, //!, /** */, and /*! */). Regular comments are used for implementation notes and debugging. Unlike C, Rust block comments (/* */) can be nested.

Documentation comments support Markdown and are processed by cargo doc to generate HTML documentation. /// documents the item immediately following it, while //! documents the enclosing module or crate. The block variants /** */ and /*! */ serve the same purposes as their line counterparts. Code blocks inside documentation comments are also executed as doc tests by cargo test, ensuring that example code stays accurate as the codebase evolves. For crates published to crates.io, documentation generated by cargo doc is displayed automatically on the crate's page.

If you find any errors or copyright issues, please .