Rust Comments
Comments in Rust let you annotate code for humans; they come in line, block, and documentation forms that the compiler ignores or specially processes.
Line Comments
The most common comment style in Rust starts with two forward slashes, //, and extends to the end of the line. Anything after // on that line is ignored by the compiler entirely.
Line comments
fn main() {
// This program calculates a discount
let price = 100;
let discount = 20; // percentage off
println!("Discounted price: {}", price - discount);
}Block Comments
Rust also supports block comments delimited by /* and */, which can span multiple lines. Unlike in C, Rust's block comments can be nested inside one another, which makes it safe to comment out a chunk of code that already contains a block comment.
Block comments
fn main() {
/* This block explains the constant below.
It can span as many lines as needed. */
let max_retries = 3;
println!("Max retries: {}", max_retries);
}Documentation Comments
Beyond ordinary comments, Rust has a special third form: documentation comments, written with /// above an item or //! at the top of a module. Tools like cargo doc read these comments and generate browsable HTML API documentation automatically, and they can even contain runnable code examples that cargo test executes as tests.
Documentation comments
/// Adds two numbers together and returns the sum.
///
/// # Examples
///
/// let result = add(2, 3);
/// assert_eq!(result, 5);
fn add(a: i32, b: i32) -> i32 {
a + b
}
fn main() {
println!("2 + 3 = {}", add(2, 3));
}- // starts a line comment that runs to the end of the line
- /* ... */ starts a block comment, and Rust allows nesting them
- /// documents the item immediately below it (a function, struct, or enum)
- //! documents the enclosing item, typically used at the top of a file or module
- Comments have zero effect on the compiled binary or its performance
Exercise: Rust Comments
How do you write a single-line comment in Rust?