Rust supports two types of comments: normal inline (//) or multi-line (/* … */) for explaining your code, and special documentation comments that generate public-facing docs. Writing clear comments is key to keeping your Rust code readable and maintainable.
One thing I learned early in Rust is that clear code is not always self-explanatory. Like any language, good comments help future readers (and your future self) understand the why behind your logic. But Rust also encourages documenting code in a way that tools can read and generate nice HTML pages—just like how crates.io docs work.
In this post, I will walk you through writing comments and documentation the idiomatic Rust way.
Inline Comments (Single Line)
Rust uses double slashes for regular comments:
// This is a single-line comment
let x = 42; // You can also put it at the end of a line
Use these to clarify logic, note edge cases, or explain why a change was made.
Multi-line Comments
You can write longer comments using slash + star:
/*
This is a multi-line comment.
Use it when you want to write blocks of explanation.
*/
But this is less common than multiple single-line comments in Rust.
Documentation Comments
Rust has built-in support for writing developer documentation that gets turned into web pages. Use triple slashes (///):
/// Adds two numbers together.
///
/// # Examples
///
/// ```
/// let sum = add(2, 3);
/// assert_eq!(sum, 5);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
This kind of comment is meant for external users of your function or module. It supports Markdown and even embedded examples.
Documenting Structs, Enums, and Modules
You can document any public item:
/// A Rectangle with width and height.
pub struct Rectangle {
pub width: u32,
pub height: u32,
}
For enums:
/// Represents the direction of movement.
pub enum Direction {
Up,
Down,
Left,
Right,
}
For modules, add the comment above the mod keyword or in the mod.rs file:
/// Math utilities module
pub mod math {
// ...
}
Running Documentation Locally
To generate and view your docs:
cargo doc --open
This builds your documentation and opens it in your browser.
You will see nicely formatted pages for your crates, functions, and types just like official docs on docs.rs.
Common Sections in Doc Comments
Use headings like this in your documentation:
- # Examples – show how to use the item
- # Arguments – describe function parameters
- # Returns – explain what it gives back
- # Panics – note if it might panic
- # Errors – describe the Err case in Result
These are not enforced, but they are widely used and help readers.
Using //! for Crate or File-Level Docs
Use //! at the top of a file or module to describe the whole file:
//! This module provides math utilities for vectors and geometry.
This is great for crate-level documentation in lib.rs.
In-Doc Tests
Rust will run the code examples inside your documentation as tests:
/// Returns the square of a number.
///
/// ```
/// let result = my_crate::square(4);
/// assert_eq!(result, 16);
/// ```
Run them with:
cargo test
This ensures your documentation stays correct.
Summary Table
Type | Syntax | Use For |
---|---|---|
Comment | // | Internal notes and explanations |
Multi-line Comment | /* */ | Temporary or longer blocks (rare) |
Doc Comment | /// | Public documentation, Markdown-enabled |
Module Doc | //! | File- or module-level documentation |
Rust Learning Path
- Introduction to Rust
- Setting Up Rust Development Environment
- Your First Rust Program
- Variables and Mutability in Rust
- Constants and Immutability in Rust
- Type Annotations and Inference in Rust
- Variable Shadowing and Scope in Rust
- Rust Primitive Data Types
- Working with Strings in Rust
- Every Operator in Rust Explained
- Tuples in Rust
- Arrays and Slices in Rust
- Rust Decision Making: if & match
- Loops in Rust
- Reading Input from the Console in Rust
- Mastering Rust Functions (For Beginners)
- Understanding Ownership in Rust
- Borrowing and References in Rust
- Copy Types vs. Move Semantics in Rust
- Cloning Data in Rust
- Methods and Associated Functions in Rust
- Enums: Defining Variant Types in Rust
- Pattern Matching with Enums in Rust
- The Option Type: Null Safety in Rust
- Error Handling with Result
- Unrecoverable Errors in Rust
- Organizing Code with Modules in Rust
- Cargo Basics: Rust Package Manager
- How to Use External Crates in Rust