Start with the idea
/// documents the item that follows and //! documents the enclosing module or crate. Code blocks inside doc comments are compiled and executed by cargo test, so an example that drifts out of date fails the build instead of quietly misleading the next reader.
Comments are most useful when they preserve a reason the code alone cannot show. // is suitable for a local decision, such as why a limit exists or why a case is skipped. Repeating the next expression in English makes the reader maintain two copies of the same fact. If the code needs a long explanation of what it does, first see whether clearer names or a smaller function would help.
Documentation comments have a different audience. Place /// immediately before an item to explain its purpose, parameters, return value, and conditions that matter to callers. Use //! for an overview of the containing module or crate. A short example makes the contract concrete: it should demonstrate a representative call and assert the expected result. In a Cargo project, cargo test runs valid Rust code blocks in documentation as doctests.
Keep learning, for free
The rest of this lesson is waiting for you.
Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.
No payment details. Your account opens the complete Academy.