Open In App

Rust – Comments

Last Updated : 17 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In Rust programming, a comment is a programmer-readable explanation or annotation in the source code of a computer program. Comments are statements that are not executed by the compiler and interpreter. To write comments in Rust, we have two types of comments as in any other programming language.

  • Non-doc Comments
    • Single-Line Comments
    • MultiLine Comments
  • Doc Comments
    • Outer doc comments
    •  Inner doc comments

Single-Line Comments:

To write single-lined comments we can use the // characters before the text you want to ignore while compiling and running.

Example 1:

Rust




// Rust code for a single line comment
fn main() {
    println!("Hello, world!");
      //this text is ignored
}


Output:

 

As we can the code inside the comment was not complied with and hence didn’t generate any error.

Multi-line comments:

Using multi-line comments we can ignore multiple lines in the source code file. We begin the comment with /* and end the comment with */

Example 2:

Rust




// Rust code for Multiline comments
fn main() {
    println!("Hello, world!");
    /* this is a
    Multiline
    comment
    */
    println!("Hello, Geeks!")
}


Output:

 

Doc comments:

Rust also has doc comments which can be used to document a particular entity in the source code, that can be a function, struct, or any other entity. We can use as follows:

  • Outer doc comments
  • Inner doc comments

Outer Doc comments:

We use outer doc comments to document some code outside the block. It helps in knowing the high-level overview of the entity in the code.

Example 3:

Rust




// Rust code for main function
// simply prints hello geeks
fn main() {
   println!("Hello, Geeks!")
}


Output:

 

Inner Doc comments:

The inner documentation comment can be used to get fine-grain documentation inside the block of code. This can be used with //! 

Example 4:

Rust




// Rust code for inner doc comments
fn main() {
    greet()
}
 
/// greet function simply prints hello geeks
fn greet(){
    //! This is a simple greet
    println!("Hello, Geeks!")
}


Output:

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads