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
| Type | Syntax | Description |
|---|---|---|
| Single-line comment | // text | Everything 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 | /// text | Documents the item immediately following it (function, struct, enum, module, etc.). Supports Markdown syntax. |
| Crate/module doc comment | //! text | Documents 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.
| Convention | Description |
|---|---|
| ```rust ... ``` | Code block. Executed as a doc test by cargo test. |
| # Examples | Section for usage examples. The heading "Examples" is the conventional name. |
| # Panics | Documents conditions under which the function panics. |
| # Errors | Documents conditions under which Result::Err is returned. |
| # Safety | Documents the safety conditions required when calling an unsafe function. |
When to Write Comments and When Not To
| Decision | Situation | Reason |
|---|---|---|
| Write a comment | The reason why something was implemented a certain way | Design decisions and trade-offs that cannot be understood from the code alone help your future self and other developers. |
| Write a comment | Complex algorithms or formulas | Add a brief description of what a piece of logic does when its behavior is not immediately obvious at a glance. |
| Write a comment | Public API functions, structs, and traits | Adding /// doc comments allows cargo doc to generate HTML documentation, which also appears automatically on crates.io. |
| Write a comment | Safety conditions for unsafe blocks | Documenting why the code is safe helps future maintainers verify correctness after changes. |
| No comment needed | Logic that is obvious from reading the code | Self-evident explanations become noise. Clear variable and function names remove the need for such comments. |
| No comment needed | Change history or deleted code | Because 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 contact us.