Documentation Comments
In this page:
Documenting a Function with ///
Placing /// comments directly above a function describes what it does, and cargo doc uses this text to generate that function's documentation page.
Example: Documenting a Function with ///
/// Calculates the area of a rectangle given its width and height.
fn area(width: f64, height: f64) -> f64 {
width * height
}
fn main() {
println!("Area: {}", area(3.0, 4.0));
}
Login to try C/C++/Java/PHP code in the editor
Documenting a Module with //!
//! comments, usually placed at the very top of a file, document the enclosing item itself (like the whole module) rather than whatever code follows them.
Example: Documenting a Module with //!
//! This module provides simple geometry helper functions.
fn perimeter(width: f64, height: f64) -> f64 {
2.0 * (width + height)
}
fn main() {
println!("Perimeter: {}", perimeter(3.0, 4.0));
}
Login to try C/C++/Java/PHP code in the editor
Including a Usage Example
Good documentation comments often include a fenced code example showing how to call the function, which is both helpful to readers and doubles as an automatically-run doc test.
Example: Including a Usage Example
/// Converts Celsius to Fahrenheit.
///
/// ```
/// let f = my_project::to_fahrenheit(0.0);
/// assert_eq!(f, 32.0);
/// ```
pub fn to_fahrenheit(celsius: f64) -> f64 {
celsius * 9.0 / 5.0 + 32.0
}
fn main() {
println!("{}", to_fahrenheit(0.0));
}
Login to try C/C++/Java/PHP code in the editor
Generating HTML Docs
cargo doc --open builds a full HTML documentation site from all the doc comments in a project and opens it directly in your web browser.
Example: Generating HTML Docs
cargo doc --open
⚠️ Run this command in your terminal.
- Using regular
//comments when///is needed for the comment to actually be picked up as documentation bycargo doc. - Forgetting
//!documents the enclosing item (like a whole module) rather than the next item that follows it. - Not including a runnable example in doc comments for public functions, missing an easy opportunity for a free doc test.
///documents the item immediately following it, such as a function or struct.//!documents the enclosing item itself, commonly used at the top of a module or crate.cargo doc --opengenerates HTML documentation from these comments and opens it in a browser.- Well-written doc comments often include a runnable example, which doubles as a doc test.
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: