Comments

All programmers strive to make their code easy to understand, but sometimes extra explanation is warranted. In these cases, programmers leave notes, or comments, in their source code that the compiler will ignore but people reading the source code may find useful.

Here’s a simple comment:

  1. # #![allow(unused_variables)]
  2. #fn main() {
  3. // hello, world
  4. #}

In Rust, comments must start with two slashes and continue until the end of the line. For comments that extend beyond a single line, you’ll need to include // on each line, like this:

  1. # #![allow(unused_variables)]
  2. #fn main() {
  3. // So we’re doing something complicated here, long enough that we need
  4. // multiple lines of comments to do it! Whew! Hopefully, this comment will
  5. // explain what’s going on.
  6. #}

Comments can also be placed at the end of lines containing code:

Filename: src/main.rs

  1. fn main() {
  2. let lucky_number = 7; // I’m feeling lucky today
  3. }

But you’ll more often see them used in this format, with the comment on a separate line above the code it’s annotating:

Filename: src/main.rs

  1. fn main() {
  2. // I’m feeling lucky today
  3. let lucky_number = 7;
  4. }

Rust also has another kind of comment, documentation comments, which we’ll discuss in Chapter 14.