5.10 Comments in Rust
Comments clarify code for future readers and maintainers. Rust supports two main comment styles.
5.10.1 Regular Comments
-
Single-line:
#![allow(unused)] fn main() { // This is a single-line comment let x = 5; // Comments can follow code on the same line }
-
Multi-line:
#![allow(unused)] fn main() { /* This is a multi-line comment. It can span many lines. Rust supports nested block comments, so you can comment out code that itself contains comments. */ }
5.10.2 Documentation Comments
Documentation comments are processed by rustdoc
to generate HTML documentation. They come in two variants:
- Outer (
///
or/** ... */
): Documents the next item (function, struct, etc.). - Inner (
//!
or/*! ... */
): Documents the containing module or crate.
#![allow(unused)] fn main() { //! A library for arithmetic operations /// Adds two numbers. /// /// # Example /// /// ``` /// let result = add(5, 3); /// assert_eq!(result, 8); /// ``` fn add(a: i32, b: i32) -> i32 { a + b } }
You can also use /** ... */
or /*! ... */
for multi-line documentation comments if you prefer.
5.10.3 Guidelines
- Focus on why the code does something rather than what it does; the code typically shows what.
- Use line comments (
//
) for short remarks, and block comments (/* ... */
) for temporarily disabling code or longer explanations. - Public APIs in libraries should have
///
comments with usage examples.