🎓 A1Learner
🔍

Rust Comments

Comments are notes in your code that the computer ignores. Rust has comments for short notes, and a special kind of comment that becomes documentation.

A note on one line

Two slashes start a comment. The compiler ignores everything after them:

let total = 2 + 3; // add the two numbers

Block comments can nest

A note between /* and */ can span lines. Blocks can sit inside blocks. So you can comment out code that already holds block comments:

/* outer note
   /* inner note */
   still a comment */
let total = 5;

A comment inside an expression

The middle of a line can be commented out too. Here the 90 + is ignored, so x is 5 + 5:

let x = 5 + /* 90 + */ 5;
println!("x = {}", x);

Comments that become documentation

Three slashes write documentation for the item after them. Cargo can turn these into a web page:

/// Greets the reader.
fn main() {
    println!("Hello, Ferris!");
}

Names follow a pattern

Variables and functions use snake_case, types use PascalCase, and constants use SCREAMING_SNAKE_CASE:

let total_score = 5;

Two Cargo helpers

cargo fmt formats your code the standard way. cargo clippy reads it and offers extra tips:

// in your terminal:
// $ cargo fmt
// $ cargo clippy

Example

/// Prints a small total.
///
/// The total is the sum of 2 and 3.
fn main() {
    let total_score = 2 + 3; // snake_case
    println!("total = {}", total_score);
}

Key points

  • Comments are written for people, not for the machine.

In this example, the lines starting with /// are documentation for main. They explain what the program does. Cargo can turn these comments into a web page. In main, the variable total_score uses snake_case, as Rust style asks. total_score holds 2 + 3. So the println! prints total = 5.

Note

/// documents the item after it, while //! documents the whole file or module it sits in — the Documentation lesson uses both

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

Which of these names follows Rust style for a function?