Rust Comments Explanation and Annotation

RustRustBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

Welcome to Comments. This lab is a part of the Rust Book. You can practice your Rust skills in LabEx.

In this lab, you will learn about comments in Rust and how they are used to provide explanations and annotations in source code for better understanding.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("`Rust`")) -.-> rust/BasicConceptsGroup(["`Basic Concepts`"]) rust(("`Rust`")) -.-> rust/FunctionsandClosuresGroup(["`Functions and Closures`"]) rust/BasicConceptsGroup -.-> rust/variable_declarations("`Variable Declarations`") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("`Function Syntax`") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("`Expressions and Statements`") subgraph Lab Skills rust/variable_declarations -.-> lab-100390{{"`Rust Comments Explanation and Annotation`"}} rust/function_syntax -.-> lab-100390{{"`Rust Comments Explanation and Annotation`"}} rust/expressions_statements -.-> lab-100390{{"`Rust Comments Explanation and Annotation`"}} end

Comments

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

Here's a simple comment:

// hello, world

In Rust, the idiomatic comment style starts a comment with two slashes, and the comment continues until the end of the line. For comments that extend beyond a single line, you'll need to include // on each line, like this:

// So we’re doing something complicated here, long enough that we need
// multiple lines of comments to do it! Whew! Hopefully, this comment will
// explain what’s going on.

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

Filename: src/main.rs

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

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

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

Rust also has another kind of comment, documentation comments, which we'll discuss in "Publishing a Crate to Crates.io".

Summary

Congratulations! You have completed the Comments lab. You can practice more labs in LabEx to improve your skills.

Other Rust Tutorials you may like