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.
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);}
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);}
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);}
/// 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 overflowpub 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('@') }}
//! 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('@') }}
/// 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 formatpub async fn fetch_data(url: &str) -> Result<String, NetworkError> { // Implement network request Ok("Simulated data".to_string())}#[derive(Debug)]pub enum NetworkError { Timeout, ConnectionRefused,}
/// 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");}
// 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;}
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
Block Comments
Commented Code
📚 Documentation Comments
External Documentation Comments
Internal Documentation Comments
📖 Documentation Examples and Tests
Runnable Documentation Examples
Documentation Comment Special Markers
🔧 Conditional Compilation Comments
Configuration-Related Comments
📝 Comment Best Practices
Good Comment Habits
Bad Comment Examples
🛠️ Documentation Generation
Cargo Documentation Commands
Documentation Configuration
📝 Chapter Summary
Through this chapter, you should have mastered:
Comment Types
Documentation Best Practices
Issues to Avoid
Continue learning: Next chapter - Rust Functions