rust / beginner
Snippet
Writing Comments in Rust Code
Rust supports three types of comments. Single-line comments start with `//` and extend to the end of the line. Multi-line comments are enclosed between `/*` and `*/` and can span multiple lines. Documentation comments are special comments that start with `///` and are used to generate documentation for public items. Documentation comments support Markdown formatting and can include sections like Arguments, Returns, and Examples. Comments are completely ignored by the compiler and serve to make code more readable and maintainable.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// This is a single-line comment explaining the main functionfn main() {// Inline comment inside the functionlet x = 10; // This variable holds the value 10/* This is a multi-line comment.It can span multiple lines.Useful for longer explanations. */let y = 20;/// Documentation comment for the calculate function/// Calculates the sum of two numbers/// # Arguments/// * `a` - first number/// * `b` - second number/// # Returns/// The sum of a and bfn calculate(a: i32, b: i32) -> i32 {a + b}println!("Result: {}", calculate(x, y));}
Breakdown
1
// This is a single-line comment
Single-line comment explaining the code below it
2
let x = 10; // This variable holds...
Inline comment after code on the same line
3
/* This is a multi-line comment... */
Multi-line comment block spanning several lines
4
/// Documentation comment...
Documentation comment for generating API docs
5
/// # Arguments
Markdown section within doc comment listing parameters
6
fn calculate(a: i32, b: i32) -> i32 {
Public function with doc comments describing its purpose and usage