Rust Comments
A comment is a note in your code that the compiler skips completely. Comments are for people: for a classmate reading your program, for a teammate, and very often for yourself in three weeks, when you have forgotten why you wrote something the way you did.
Line comments
Two slashes // start a comment that runs to the end of the line. You can put one on its own line, or after some code:
fn main() {
// Work out the area of a rectangle
let width = 8;
let height = 5;
println!("Area: {}", width * height); // 8 times 5
}Area: 40
Block comments
For a longer note you can use /* to start and */ to end. Everything between them is a comment, even across several lines. Rust programmers mostly use // on every line instead, but it is good to recognise both.
fn main() {
/*
This program greets the user.
Later we will ask for their name.
*/
println!("Hello!");
}Hello!
Switching code off
Comments are also a wonderful tool while you are learning. If you are not sure what a line does, put // in front of it and run the program again. The line is now ignored, and you can see the difference it makes. Remove the slashes to bring it back.
fn main() {
println!("Line one");
// println!("Line two is switched off");
println!("Line three");
}Line one Line three
What makes a good comment
Good comments explain why, not just what. A comment like // add one above count += 1 tells the reader nothing new. A comment like // the list starts at zero, people count from one explains a decision. Short, friendly, honest notes are the most useful kind.
Rust also has documentation comments, which start with three slashes /// and describe the function or type below them. Tools can turn them into a website of documentation. You will see them in other people's code, and you can use them in yours.
Practice exercises
- Add a comment above each line of one of your earlier programs that explains why the line is there.
- Switch one line off with
//, run the program, then switch it back on. - Write a block comment at the top of a program with your name and the date.