2.17 Comments and Documentation
Rust supports several forms of comments, including special syntax for generating documentation.
2.17.1 Regular Comments
- // Single-line comment: Extends to the end of the line.
- /* Multi-line comment */: Can span multiple lines. These can be nested.
#![allow(unused)] fn main() { // Calculate the square of a number fn square(x: i32) -> i32 { /* This function takes an integer, multiplies it by itself, and returns the result. */ x * x } }
2.17.2 Documentation Comments (rustdoc)
Rust has built-in support for documentation generation via the rustdoc tool, which processes special documentation comments written in Markdown.
- /// Doc comment for the item following it: Used for functions, structs, modules, etc.
- //! Doc comment for the enclosing item: Used inside a module or crate root (- lib.rsor- main.rs) to document the module/crate itself.
//! This module provides utility functions for string manipulation. /// Reverses a given string slice. /// /// # Examples /// /// ``` /// let original = "hello"; /// # // We might hide the module path in the rendered docs for simplicity, /// # // but it's needed here if `reverse` is in `string_utils`. /// # mod string_utils { pub fn reverse(s: &str) -> String { s.chars().rev().collect() } } /// let reversed = string_utils::reverse(original); /// assert_eq!(reversed, "olleh"); /// ``` /// /// # Panics /// This function might panic if memory allocation fails (very unlikely). pub fn reverse(s: &str) -> String { s.chars().rev().collect() } // (Module content continues...) // Need a main function for the doctest harness to work correctly fn main() { mod string_utils { pub fn reverse(s: &str) -> String { s.chars().rev().collect() } } let original = "hello"; let reversed = string_utils::reverse(original); assert_eq!(reversed, "olleh"); }
Running cargo doc builds the documentation for your project and its dependencies as HTML files, viewable in a web browser. Code examples within /// comments (inside triple backticks  ) are compiled and run as tests by cargo test, ensuring documentation stays synchronized with the code.
Multi-line doc comments /** ... */ (for following item) and /*! ... */ (for enclosing item) also exist but are less common than /// and //!.