← Back to Rust Course | Chapter 1: Setup & Basics | Lesson 6 of 7

Writing Comments

Comments are little notes you leave in your code that the computer ignores but people can read to understand what is going on.

Line Comments

A double slash // starts a comment that continues to the end of that line. Everything after // on that line is ignored by the compiler and exists purely for human readers.

Example: Line Comments

markup
// This program greets the user
fn main() {
    println!("Hello!"); // print a greeting
}

Block Comments

A block comment starts with /* and ends with */, and can span multiple lines. It is useful for temporarily disabling a chunk of code or writing longer explanations.

Example: Block Comments

markup
/*
   This program demonstrates block comments.
   Everything in here is ignored by the compiler.
*/
fn main() {
    println!("Block comments can span multiple lines");
}

Documentation Comments

Triple-slash /// comments placed directly above a function or item are documentation comments. Tools like cargo doc read them to automatically generate HTML documentation for your code.

Example: Documentation Comments

markup
/// Prints a friendly greeting to standard output.
fn greet() {
    println!("Hello from a documented function!");
}

fn main() {
    greet();
}

Comments Do Not Affect Execution

No matter how much text you put in comments, the compiled program behaves identically because the compiler strips comments before compilation even begins. This makes comments completely free to add for clarity.

Example: Comments Do Not Affect Execution

markup
fn main() {
    let x = 5; // this comment does nothing to the value
    println!("x is {}", x);
}
Common Mistakes
  1. Believing comments are executed or affect the program's behavior in any way -- the compiler skips them entirely.
  2. Using comments to explain *what* obvious code does instead of *why* a non-obvious decision was made.
  3. Forgetting that // only comments to the end of the line, so leftover code after it on the same line is not commented out.
Chapter Summary
  • // starts a line comment that runs to the end of the line.
  • /* ... */ starts a block comment that can span multiple lines.
  • /// before an item creates a documentation comment used by tools like cargo doc.
  • Comments are ignored by the compiler and have zero effect on the compiled program.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.