Rust Comments

Rust Tutorial

🦀 Rust Comments

In Rust Comments are used to explain code, make it readable, and generate documentation.

They are ignored by the compiler and do not affect program execution.


 1. Single-Line Comments

Use // for single-line comments.

fn main() {
// This is a single-line comment
println!("Hello, Rust!");
}

 2. Multi-Line Comments

Use /* ... */ for multi-line comments.

fn main() {
/*
This is a multi-line comment
written across several lines
*/

println!("Rust is awesome!");
}

⚠️ Multi-line comments can be nested in Rust (unlike C/C++).

Example:

/*
Outer comment
/* Inner comment */
*/

 3. Inline Comments

Used at the end of a line.

let x = 10; // storing value 10

 4. Documentation Comments (Very Important)

It supports documentation comments that generate docs using rustdoc.

▶️ Line Doc Comment (///)

Used to document items like functions, structs, enums.

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

▶️ Block Doc Comment (/** ... */)

/**
* Multiplies two numbers
*/

fn multiply(a: i32, b: i32) -> i32 {
a * b
}

 5. Module / Crate Documentation (//!)

Used at the top of files or modules.

//! This module handles math operations

fn square(x: i32) -> i32 {
x * x
}


 6. Commenting Out Code (Debugging)

fn main() {
// println!("This line is disabled");
println!("Active line");
}

 7. Best Practices for Comments

✔ Explain why, not what
✔ Use doc comments for public APIs
✔ Keep comments short & meaningful
✔ Update comments when code changes

❌ Avoid obvious comments:

let x = 5; // x is 5 ❌

🔑 Summary

Comment Type Syntax
Single-line //
Multi-line /* */
Doc (item) ///
Doc (module) //!

You may also like...