Skip to content

Rust Comments

Overview

Comments are an important component of code, used to explain code logic, generate documentation, mark to-do items, etc. Rust provides various comment styles. This chapter will introduce various comment syntaxes and best practices in detail.

💬 Basic Comments

Line Comments

rust
fn line_comments() {
    // This is a single-line comment
    let x = 5; // End-of-line comment

    // Multi-line comments can be written like this
    // Each line needs double slashes
    // These comments are clear

    let y = 10;

    // TODO: Implement more complex logic
    // FIXME: Fix performance issue here
    // NOTE: Need special attention here
    // HACK: Temporary solution

    println!("x: {}, y: {}", x, y);
}

Block Comments

rust
fn block_comments() {
    /*
     * This is a block comment
     * Can span multiple lines
     * Usually used for large blocks of comments
     */
    let message = "Hello, World!";

    /* Simple block comment */
    let number = 42;

    /*
    Block comments can be nested
    /*
        Like this nested
        /* Even can have multiple levels of nesting */
    */
    */

    println!("{}: {}", message, number);
}

Commented Code

rust
fn commented_code() {
    let active_code = "This line will execute";

    // let commented_code = "This line will not execute";

    /*
    let block_commented = "This code";
    let all_commented = "will not execute";
    */

    println!("{}", active_code);
}

📚 Documentation Comments

External Documentation Comments

rust
/// Calculate the sum of two numbers
///
/// # Arguments
///
/// * `a` - The first number
/// * `b` - The second number
///
/// # Returns
///
/// Returns the sum of two numbers
///
/// # Examples
///
/// ```
/// use my_crate::add;
///
/// let result = add(2, 3);
/// assert_eq!(result, 5);
/// ```
///
/// # Note
///
/// This function may overflow
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

/// Represents a user struct
///
/// # Fields
///
/// * `id` - Unique identifier for the user
/// * `name` - User's name
/// * `email` - User's email address
///
/// # Examples
///
/// ```
/// use my_crate::User;
///
/// let user = User {
///     id: 1,
///     name: String::from("Alice"),
///     email: String::from("alice@example.com"),
/// };
///
/// println!("User: {}", user.name);
/// ```
pub struct User {
    /// User ID
    pub id: u32,
    /// User name
    pub name: String,
    /// User email
    pub email: String,
}

impl User {
    /// Create a new user
    ///
    /// # Arguments
    ///
    /// * `name` - User name
    /// * `email` - User email
    ///
    /// # Returns
    ///
    /// Returns a newly created user instance
    ///
    /// # Examples
    ///
    /// ```
    /// use my_crate::User;
    ///
    /// let user = User::new("Bob".to_string(), "bob@example.com".to_string());
    /// assert_eq!(user.name, "Bob");
    /// ```
    pub fn new(name: String, email: String) -> Self {
        Self {
            id: 0, // Simplified example
            name,
            email,
        }
    }

    /// Check if user is valid
    ///
    /// # Returns
    ///
    /// Returns `true` if user information is valid, otherwise returns `false`
    ///
    /// # Examples
    ///
    /// ```
    /// use my_crate::User;
    ///
    /// let user = User::new("Charlie".to_string(), "charlie@example.com".to_string());
    /// assert!(user.is_valid());
    /// ```
    pub fn is_valid(&self) -> bool {
        !self.name.is_empty() && self.email.contains('@')
    }
}

Internal Documentation Comments

rust
//! This is a module-level documentation comment
//!
//! This module provides user management functionality
//!
//! # Features
//!
//! - Create users
//! - Validate user information
//! - User data management
//!
//! # Usage
//!
//! ```
//! use user_module::User;
//!
//! let user = User::new("Alice".to_string(), "alice@example.com".to_string());
//! println!("User: {}", user.name);
//! ```

pub mod user_management {
    /*!
     * This is also a module-level documentation comment
     * Using block comment style
     */

    //! # User Management Module
    //!
    //! Provides complete user management functionality

    pub fn create_user(name: &str, email: &str) -> bool {
        // User creation logic
        !name.is_empty() && email.contains('@')
    }
}

📖 Documentation Examples and Tests

Runnable Documentation Examples

rust
/// Calculate factorial
///
/// # Arguments
///
/// * `n` - The number to calculate factorial for
///
/// # Returns
///
/// Returns the factorial of n
///
/// # Examples
///
/// ```
/// use my_crate::factorial;
///
/// assert_eq!(factorial(0), 1);
/// assert_eq!(factorial(1), 1);
/// assert_eq!(factorial(5), 120);
/// ```
///
/// # Panics
///
/// Panics when input is negative
///
/// ```should_panic
/// use my_crate::factorial;
///
/// factorial(-1); // This will panic
/// ```
pub fn factorial(n: i32) -> i32 {
    if n < 0 {
        panic!("Factorial does not support negative numbers");
    }

    match n {
        0 | 1 => 1,
        _ => n * factorial(n - 1),
    }
}

/// Division operation
///
/// # Arguments
///
/// * `dividend` - Dividend
/// * `divisor` - Divisor
///
/// # Returns
///
/// Returns the division result, returns error if divisor is 0
///
/// # Examples
///
/// ```
/// use my_crate::divide;
///
/// assert_eq!(divide(10, 2), Ok(5));
/// assert_eq!(divide(10, 3), Ok(3)); // Integer division
/// ```
///
/// # Error Handling
///
/// ```
/// use my_crate::divide;
///
/// assert!(divide(10, 0).is_err());
/// ```
///
/// # Ignored Test
///
/// ```ignore
/// // This test will be ignored
/// use my_crate::divide;
///
/// let result = divide(i32::MAX, 1);
/// ```
pub fn divide(dividend: i32, divisor: i32) -> Result<i32, String> {
    if divisor == 0 {
        Err("Cannot divide by zero".to_string())
    } else {
        Ok(dividend / divisor)
    }
}

/// Complex data structure example
///
/// ```
/// use std::collections::HashMap;
///
/// let mut map = HashMap::new();
/// map.insert("key1", "value1");
/// map.insert("key2", "value2");
///
/// assert_eq!(map.get("key1"), Some(&"value1"));
/// assert_eq!(map.get("key3"), None);
/// ```
pub fn example_with_dependencies() {
    // Function implementation
}

Documentation Comment Special Markers

rust
/// Network request function
///
/// # Safety
///
/// This function uses unsafe code, the caller needs to ensure the passed pointer is valid
///
/// # Errors
///
/// Returns error when network connection fails:
///
/// - `NetworkError::Timeout` - Connection timeout
/// - `NetworkError::ConnectionRefused` - Connection refused
///
/// # Panics
///
/// Panics when URL format is incorrect
///
/// # Examples
///
/// ```no_run
/// // This example will not run during testing
/// use my_crate::fetch_data;
///
/// let data = fetch_data("https://api.example.com/data").await?;
/// println!("Data retrieved: {:?}", data);
/// ```
///
/// # See also
///
/// * [`process_data`] - Process the retrieved data
/// * [`validate_url`] - Validate URL format
pub async fn fetch_data(url: &str) -> Result<String, NetworkError> {
    // Implement network request
    Ok("Simulated data".to_string())
}

#[derive(Debug)]
pub enum NetworkError {
    Timeout,
    ConnectionRefused,
}

🔧 Conditional Compilation Comments

rust
/// Platform-specific functionality
///
/// This function has different implementations on different platforms
///
/// # Platform Support
///
/// - Windows: Full support
/// - Linux: Full support
/// - macOS: Partial support
///
/// # Examples
///
/// ```
/// use my_crate::platform_specific_function;
///
/// #[cfg(target_os = "windows")]
/// {
///     // Windows-specific code
///     platform_specific_function();
/// }
/// ```
#[cfg(target_os = "windows")]
pub fn platform_specific_function() {
    // Windows implementation
    println!("Windows version");
}

#[cfg(target_os = "linux")]
pub fn platform_specific_function() {
    // Linux implementation
    println!("Linux version");
}

#[cfg(target_os = "macos")]
pub fn platform_specific_function() {
    // macOS implementation
    println!("macOS version");
}

/// Debug functionality during development
///
/// This function is only available in debug mode
///
/// # Note
///
/// This function does not exist in release builds
///
/// # Examples
///
/// ```
/// #[cfg(debug_assertions)]
/// use my_crate::debug_function;
///
/// #[cfg(debug_assertions)]
/// debug_function();
/// ```
#[cfg(debug_assertions)]
pub fn debug_function() {
    println!("Debug information");
}

📝 Comment Best Practices

Good Comment Habits

rust
/// User authentication service
///
/// Provides user login, registration, password reset, and other functionality
///
/// # Security Considerations
///
/// - Passwords are encrypted and stored using bcrypt
/// - Login failure count limit
/// - JWT token expiration control
///
/// # Examples
///
/// ```
/// use auth_service::AuthService;
///
/// let auth = AuthService::new();
/// let result = auth.login("user@example.com", "password").await;
///
/// match result {
///     Ok(token) => println!("Login successful, token: {}", token),
///     Err(e) => println!("Login failed: {}", e),
/// }
/// ```
pub struct AuthService {
    // Private fields don't need public documentation
    connection_pool: DatabasePool,
    jwt_secret: String,
}

impl AuthService {
    /// Create a new authentication service instance
    ///
    /// # Arguments
    ///
    /// * `database_url` - Database connection string
    /// * `jwt_secret` - JWT signing key
    ///
    /// # Errors
    ///
    /// Returns error if database connection fails
    pub fn new(database_url: &str, jwt_secret: String) -> Result<Self, AuthError> {
        // Actual implementation would connect to database
        Ok(Self {
            connection_pool: DatabasePool::new(),
            jwt_secret,
        })
    }

    /// User login
    ///
    /// # Arguments
    ///
    /// * `email` - User email
    /// * `password` - User password (plaintext)
    ///
    /// # Returns
    ///
    /// Returns JWT token on success, returns error on failure
    ///
    /// # Security Notes
    ///
    /// - Password will be hash-compared inside the function
    /// - Login failures will increase failure count
    /// - Multiple failures will temporarily lock the account
    pub async fn login(&self, email: &str, password: &str) -> Result<String, AuthError> {
        // 1. Validate input parameters
        if email.is_empty() || password.is_empty() {
            return Err(AuthError::InvalidInput);
        }

        // 2. Query user information
        // let user = self.find_user_by_email(email).await?;

        // 3. Verify password
        // if !self.verify_password(password, &user.password_hash) {
        //     return Err(AuthError::InvalidCredentials);
        // }

        // 4. Generate JWT token
        // self.generate_jwt_token(&user)

        // Simplified example
        Ok("jwt_token_here".to_string())
    }

    // Private methods usually don't need detailed documentation comments
    // But can add brief descriptions

    /// Verify password hash
    fn verify_password(&self, password: &str, hash: &str) -> bool {
        // Use bcrypt to verify password
        true // Simplified example
    }

    /// Generate JWT token
    fn generate_jwt_token(&self, user_id: u32) -> Result<String, AuthError> {
        // JWT generation logic
        Ok(format!("token_for_user_{}", user_id))
    }
}

// Error types also need documentation
/// Authentication service error types
#[derive(Debug)]
pub enum AuthError {
    /// Invalid input parameters
    InvalidInput,
    /// Invalid authentication credentials
    InvalidCredentials,
    /// Database connection error
    DatabaseError,
    /// JWT token generation failure
    TokenGenerationError,
}

// Simplified type definitions
struct DatabasePool;
impl DatabasePool {
    fn new() -> Self { Self }
}

Bad Comment Examples

rust
// Don't write comments like this:

fn bad_comments_example() {
    // Create variable x
    let x = 5; // Set x to 5

    // Increment x
    let x = x + 1; // x equals x plus 1

    // Print x
    println!("{}", x); // Output x's value

    /*
     * This comment is too long, says a lot of nonsense
     * But doesn't provide any useful information
     * Just repeats what the code already expresses
     * Such comments don't help understand the code
     */
    let y = 10;
}

// Better approach:
fn good_comments_example() {
    // Calculate base value for user points
    let base_points = 5;

    // Add new user bonus points
    let total_points = base_points + 1;

    println!("User total points: {}", total_points);

    // Set system default timeout (seconds)
    let timeout_seconds = 10;
}

🛠️ Documentation Generation

Cargo Documentation Commands

bash
# Generate project documentation
cargo doc

# Generate and open documentation
cargo doc --open

# Generate documentation including private items
cargo doc --document-private-items

# Generate dependency documentation
cargo doc --no-deps

# Only check documentation examples
cargo test --doc

Documentation Configuration

toml
# Documentation configuration in Cargo.toml
[package]
name = "my_crate"
version = "0.1.0"
documentation = "https://docs.rs/my_crate"

[package.metadata.docs.rs]
# Enable all features
all-features = true
# Set default target
default-target = "x86_64-unknown-linux-gnu"
# Enable KaTeX math formula support
rustdoc-args = ["--html-in-header", "katex-header.html"]

📝 Chapter Summary

Through this chapter, you should have mastered:

Comment Types

  • ✅ Usage of line comments and block comments
  • ✅ External and internal documentation comments
  • ✅ Executable documentation examples
  • ✅ Special markers and conditional compilation

Documentation Best Practices

  • ✅ Write clear and useful comments
  • ✅ Provide complete example code
  • ✅ Use documentation markers correctly
  • ✅ Generate and publish documentation

Issues to Avoid

  1. Don't repeat code logic
  2. Avoid outdated comments
  3. Don't comment on obvious content
  4. Keep comments synchronized with code

Continue learning: Next chapter - Rust Functions

Content is for learning and research only.