Writing Comments
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
// This program greets the user
fn main() {
println!("Hello!"); // print a greeting
}
Login to try C/C++/Java/PHP code in the editor
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
/*
This program demonstrates block comments.
Everything in here is ignored by the compiler.
*/
fn main() {
println!("Block comments can span multiple lines");
}
Login to try C/C++/Java/PHP code in the editor
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
/// Prints a friendly greeting to standard output.
fn greet() {
println!("Hello from a documented function!");
}
fn main() {
greet();
}
Login to try C/C++/Java/PHP code in the editor
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
fn main() {
let x = 5; // this comment does nothing to the value
println!("x is {}", x);
}
Login to try C/C++/Java/PHP code in the editor
- Believing comments are executed or affect the program's behavior in any way -- the compiler skips them entirely.
- Using comments to explain *what* obvious code does instead of *why* a non-obvious decision was made.
- Forgetting that
//only comments to the end of the line, so leftover code after it on the same line is not commented out.
//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 likecargo 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: