Comments

Comments in Rust are a way to make your code easy to understand by writing small explanations about your code, comments are ignored by the compiler, so they don't affect the execution of your code. They can also be used in documenting your code using the rustdoc tool.

In Rust, comments can be written in two ways:

  1. Single-line comments: These comments start with // and continue until the end of the line. For example:
fn main() {
    let x = 5;
    // This is a single-line comment
}

You can also write the comment after a line of code, like this:

fn main() {
    let x = 5; // This is a single-line comment
}
  1. Multi-line comments: These comments start with /* and end with */. For example:
fn main() {
    /*
    This is a multi-line comment
    It can span multiple lines
    */
    let x = 5;
}

Learn Rust by Practice

Master Rust through hands-on coding exercises and real-world examples.

Rustdoc

Comments are also used by rustdoc, the Rust documentation tool to generate documentation for your code. You can use comments to write documentation for your functions, structs, and other items in your code.

In order to generate documentation, instead of using //, you should use /// for single-line comments and /** */ for multi-line comments. For example:

/// Takes 2 numbers as arguments and returns the sum
/// of the 2 numbers
fn add(x: i32, y: i32) -> i32 {
    x + y
}

Or using /** */:

/**
 * Takes 2 numbers as arguments and returns the sum
 * of the 2 numbers
 */
fn add(x: i32, y: i32) -> i32 {
    x + y
}

When you hover over the function name in your code editor, you should see the documentation comment displayed as a tooltip.

Function doc Function doc

You can also run rustdoc on your code to generate documentation for your project. For example, to generate documentation for a file named lib.rs, you can run:

rustdoc lib.rs

Conclusion

In this lesson, we learned about comments in Rust. Comments are a way to write small explanations write besides your code that are ignored by the compiler. They can also be used in writing documentation for your code using the rustdoc tool.


In the next lesson, we are going to learn about control flow in Rust.