Rust Comments
Comments are notes you leave in your code for humans to read. Rust completely ignores them when it compiles, so they never affect how your program runs. Good comments explain why code does something, not just what it does.
Line comments
Section titled “Line comments”The most common comment starts with //. Everything after // on that line is ignored:
fn main() { // This is a comment — Rust skips it entirely println!("Hello!"); // comments can also sit at the end of a line}Output:
Hello!Multi-line comments
Section titled “Multi-line comments”For a longer note, you can start every line with //:
fn main() { // This program greets the user. // It prints a single line of text. // Written as a first example. println!("Hello!");}Rust also supports block comments between /* and */, which can span several lines:
fn main() { /* This is a block comment. It can cover multiple lines without a // on each one. */ println!("Hello!");}In practice, most Rust code uses // even for multiple lines — it’s the community norm and works well with editor shortcuts.
Commenting out code
Section titled “Commenting out code”Comments are handy for temporarily disabling a line while you test something:
fn main() { println!("This runs"); // println!("This is switched off for now");}Documentation comments
Section titled “Documentation comments”Rust has a special kind of comment that starts with /// (three slashes). These are doc comments — they describe functions, and Rust can turn them into a browsable documentation website with cargo doc.
/// Adds two numbers together and returns the result.fn add(a: i32, b: i32) -> i32 { a + b}You don’t need doc comments yet as a beginner — just know that /// is for documentation, while // is for ordinary notes.
- Comments are notes Rust ignores; use them to explain your code.
//starts a line comment (the most common kind)./* ... */is a block comment for multiple lines.///is a doc comment used to generate documentation.