Comments & Documentation
Good comments make code easier to understand and maintain. Rust supports several types of comments, including special documentation comments that can generate beautiful HTML documentation automatically. In this lesson, you'll learn how to write effective comments and documentation in Rust.
Types of Comments
1. Line Comments
The most common type of comment starts with // and continues to the
end of the line:
// This is a line comment
let x = 5; // Comments can be at the end of lines too
2. Block Comments
For multi-line comments, use /* */:
/*
* This is a block comment
* It can span multiple lines
* Useful for longer explanations
*/
//) even for multi-line comments.
Block comments are typically reserved for temporarily commenting out code during
development.
Click Run to execute your code
Documentation Comments
Rust has special comments for documentation that support Markdown formatting and can be compiled into HTML documentation:
Outer Doc Comments (///)
Used to document the item that follows (functions, structs, modules, etc.):
/// Adds two numbers together.
///
/// # Examples
///
/// ```
/// let result = add(2, 3);
/// assert_eq!(result, 5);
/// ```
fn add(a: i32, b: i32) -> i32 {
a + b
}
Inner Doc Comments (//!)
Used to document the containing item (typically used at the top of modules or crates):
//! # My Awesome Crate
//!
//! This crate provides amazing functionality.
//!
//! ## Features
//!
//! - Fast
//! - Reliable
//! - Easy to use
# Examples- Show how to use the code# Panics- Describe when the function panics# Errors- Explain error conditions# Safety- Document unsafe code requirements
Generating Documentation with Cargo
Cargo can automatically generate HTML documentation from your doc comments:
cargo doc
This creates documentation in target/doc/. To open it in your
browser:
cargo doc --open
- Always include examples in your documentation
- Document public APIs thoroughly
- Use Markdown for formatting (headers, lists, code blocks)
- Include code examples that can be tested
- Explain the "why" not just the "what"
Markdown in Documentation
Doc comments support full Markdown syntax:
/// # Heading
///
/// **Bold text** and *italic text*
///
/// - Bullet point 1
/// - Bullet point 2
///
/// Inline code: `variable_name`
///
/// Code block:
/// ```rust
/// let x = 5;
/// ```
///
/// [Link to Rust](https://www.rust-lang.org/)
Documentation Tests
Code examples in doc comments are automatically tested when you run
cargo test:
/// Divides two numbers.
///
/// # Examples
///
/// ```
/// let result = divide(10, 2);
/// assert_eq!(result, 5);
/// ```
///
/// # Panics
///
/// Panics if the divisor is zero:
///
/// ```should_panic
/// divide(10, 0); // This will panic!
/// ```
fn divide(a: i32, b: i32) -> i32 {
if b == 0 {
panic!("Cannot divide by zero!");
}
a / b
}
```- Normal test (must compile and run successfully)```should_panic- Test should panic```no_run- Compile but don't run```ignore- Don't compile or run```compile_fail- Should fail to compile
Common Mistakes
1. Using wrong doc comment style
Wrong:
fn main() {
/// This doesn't document anything useful
let x = 5;
}
Correct:
/// Documents the function below
fn main() {
// Regular comment for code inside
let x = 5;
}
2. Over-commenting obvious code
Bad:
// Increment x by 1
x = x + 1;
Better:
// Apply discount to final price
x = x + 1;
3. Outdated comments
Problem: Comments that don't match the code
// Returns the sum of two numbers
fn multiply(a: i32, b: i32) -> i32 { // Oops!
a * b
}
Solution: Keep comments in sync with code changes
Summary
- Line comments:
//for single-line comments - Block comments:
/* */for multi-line comments - Outer doc comments:
///to document following items - Inner doc comments:
//!to document containing items - Use
cargo docto generate HTML documentation - Doc comments support Markdown formatting
- Code examples in docs are automatically tested
- Document public APIs, explain "why" not just "what"
What's Next?
Congratulations! You've completed Module 2 and learned the fundamentals of Rust
programming.
In the next module, we'll dive into Control Flow, learning how
to make decisions
with if expressions, loop with loop,
while, and for,
and control program flow with pattern matching.
Enjoying these tutorials?