Comments in Rust Programming

Rust ProgrammingServer Side ProgrammingProgramming

Comments in Rust are statements that are ignored by both the rust compiler and interpreter. They are mainly used for human understanding of the code.

Generally, in programming, we write comments to explain the working of different functions or variables or methods to whosoever is reading our code.

Comments enhance the code readability, especially when the identifiers in the code are not named properly.

In Rust, there are multiple ways in which we can declare comments. Mainly these are −

  • Single-line comments

  • Multi-line comments

  • Doc comments

In this article, we will explore all the three comments.

Single-Line comment

Single line comments in Rust are comments that extend up to a newline character. They make use of // (two forward slashes).

Syntax

// this is a comment

Example

fn main() {
   // single line comment
   // println!("also a comment");
   println!("Hello, world!");
}

In the above example,, two single line comments are present and both of them are going to be ignored by the compiler.

Output

Hello, world!

Multi-Line comment

Multi-line comments, as the name suggests are those comments that extend upto multiple lines. They make use of /* -- */

Syntax

/* this
   is
   a
   comment
*/

Example

fn main() {
   /*
      a
      multi
      line
      comment
   */
   println!("Hello, world!");
}

Output

Hello, world!

Doc comments

In Rust, Doc comments are comments that are used to specify the working of a method, function or similar identifiers.

We write doc comments in Rust, using the /// (three forward slashes)

Syntax

/// doc comment

A simple example in Rust,

/// This function returns the greeting; Hello, world!
pub fn hello() -> String {
   ("Hello, world!").to_string()
}
raja
Published on 21-May-2021 12:22:25
Advertisements