Rust Comments

Documenting your Rust code effectively

💬 Rust Comments Guide

Master Rust's commenting system for clear code documentation. Learn line comments, block comments, and documentation comments. Rust's comment system supports automatic documentation generation and helps maintain readable, well-documented codebases for collaborative development.


// This is a line comment
fn main() {
    /* This is a block comment */
    let x = 5; // Inline comment
    
    /// Documentation comment for functions
    /// This appears in generated docs
    println!("Hello, Rust!"); // Output greeting
}
                                    

Output:

Hello, Rust!

Types of Comments

➡️

Line Comments

Single line comments with //

// This is a line comment
let x = 5; // Inline comment
📦

Block Comments

Multi-line comments with /* */

/* This is a
   block comment */
📚

Doc Comments

Documentation with /// or //!

/// Adds two numbers
fn add(a: i32, b: i32) -> i32 {
🏷️

Module Docs

Module-level documentation

//! This module handles math
//! operations like addition

🔹 Line Comments

The most common way to add comments in Rust:

fn main() {
    // This is a single line comment
    // It explains what the code below does
    let name = "Rust";
    
    let age = 15; // Rust was first released in 2010, stable in 2015
    
    // You can use multiple line comments
    // to explain complex logic or provide
    // detailed information about your code
    
    println!("Language: {}, Age: {} years", name, age);
    
    // Comments are ignored by the compiler
    // They don't affect program execution
    // But they help other developers understand your code
}

Output:

Language: Rust, Age: 15 years

🔹 Block Comments

Use block comments for multi-line explanations:

fn main() {
    /*
     * This is a block comment
     * It can span multiple lines
     * Useful for longer explanations
     */
    
    let numbers = vec![1, 2, 3, 4, 5];
    
    /* 
       Block comments can be used to temporarily
       disable code during development:
       
       let unused_variable = "This won't run";
       println!("This is commented out");
    */
    
    /* You can also use block comments inline */ let x = 42;
    
    println!("Numbers: {:?}", numbers);
    println!("Value: {}", x);
}

Output:

Numbers: [1, 2, 3, 4, 5]

Value: 42

🔹 Documentation Comments

Special comments that generate documentation:

/// Calculates the area of a rectangle
/// 
/// # Arguments
/// 
/// * `width` - The width of the rectangle
/// * `height` - The height of the rectangle
/// 
/// # Examples
/// 
/// ```
/// let area = calculate_area(5.0, 3.0);
/// assert_eq!(area, 15.0);
/// ```
fn calculate_area(width: f64, height: f64) -> f64 {
    width * height
}

/// Represents a person with a name and age
struct Person {
    /// The person's full name
    name: String,
    /// The person's age in years
    age: u32,
}

impl Person {
    /// Creates a new Person
    /// 
    /// # Arguments
    /// 
    /// * `name` - The person's name
    /// * `age` - The person's age
    fn new(name: String, age: u32) -> Person {
        Person { name, age }
    }
}

fn main() {
    let area = calculate_area(10.0, 5.0);
    println!("Rectangle area: {}", area);
    
    let person = Person::new("Alice".to_string(), 30);
    println!("Person: {} ({})", person.name, person.age);
}

Output:

Rectangle area: 50

Person: Alice (30)

🔹 Module Documentation

Document entire modules with inner doc comments:

//! # Math Utilities Module
//! 
//! This module provides basic mathematical operations
//! and utility functions for common calculations.
//! 
//! ## Features
//! 
//! - Basic arithmetic operations
//! - Geometric calculations
//! - Number utilities

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

/// Multiplies two integers
fn multiply(a: i32, b: i32) -> i32 {
    a * b
}

fn main() {
    let sum = add(10, 20);
    let product = multiply(4, 5);
    
    println!("Sum: {}", sum);
    println!("Product: {}", product);
    
    // You can generate documentation with: cargo doc --open
}

Output:

Sum: 30

Product: 20

🔹 Best Practices

Follow these guidelines for effective commenting:

Good Commenting Practices:

  • Explain Why, Not What: Focus on the reasoning behind the code
  • Keep Comments Updated: Update comments when you change code
  • Use Doc Comments: Document public APIs with ///
  • Be Concise: Write clear, brief explanations
  • Use Examples: Include code examples in documentation
fn main() {
    // Good: Explains why we're doing this
    // Using a larger buffer size to improve performance for large files
    let buffer_size = 8192;
    
    // Bad: Just repeats what the code does
    // Set buffer_size to 8192
    
    // Good: Explains complex logic
    // Convert temperature from Celsius to Fahrenheit
    // Formula: F = (C × 9/5) + 32
    let celsius = 25.0;
    let fahrenheit = (celsius * 9.0 / 5.0) + 32.0;
    
    println!("{}°C = {}°F", celsius, fahrenheit);
    
    // Use TODO comments for future improvements
    // TODO: Add error handling for invalid temperatures
    // TODO: Support Kelvin conversion
}

Output:

25°C = 77°F

🧠 Test Your Knowledge

Which comment type generates documentation?