Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 132 ยท Getting Started

Comments and Documentation

Learn Rust comments - line and block comments, /// and //! doc comments with Markdown, doc tests, rustdoc, and how #[allow], #[warn] and #[deny] control compiler lints.

Good code explains what it does through clear names and structure. Comments explain the things code cannot say: why a decision was made, what a tricky piece assumes, how to use a public function, or which bug a strange line works around. Rust has ordinary comments for the people reading the source, and special documentation comments that become the web pages you see on docs.rs. It also has a lint system, controlled with attributes, that decides which compiler warnings you tolerate.

This lesson covers all three: regular comments, doc comments (with Markdown and tested examples), and the allow, warn and deny attributes. The previous lesson showed where cargo doc and cargo test fit in a project.

Ordinary comments

A line comment starts with // and runs to the end of the line. A block comment starts with /* and ends with */. Rust block comments nest, which is different from C and Java: you can comment out a region that already contains a block comment.

Rust Line and block comments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Nesting makes it safe to temporarily disable a big chunk of code that already has block comments in it. The Rust style guide asks for line comments (//) in nearly all cases and reserves block comments for the odd case, and rustfmt keeps both neatly indented.

What to write in a comment

Comments rot: code changes and the comment stays behind, lying. Write comments that stay true.

  • Explain why, not what. // add one to the counter next to counter += 1; is noise. // the server counts rows from 1, ours from 0 is valuable.
  • Document surprises: a workaround, a performance trick, a rule the compiler cannot check.
  • Link to the source of a magic number or algorithm, such as a specification section.
  • Mark unfinished work with TODO: or FIXME:. Tools find them, and todo!() (a macro that panics) marks code that does not exist yet.
  • Do not leave dead code in comments. Version control remembers old code for you.

Rust gives you a few places where the compiler itself replaces a comment: the type system documents what a function accepts and returns, a Result documents that something may fail, and an enum documents the possible states. Reach for a comment only after you have exhausted those.

Documentation comments

Three slashes, ///, start a doc comment. It documents the item that comes right after it (a function, struct, enum variant, field, trait, ...). Inside, you write Markdown: paragraphs, lists, code and fenced code blocks. Tools such as cargo doc turn this into browsable HTML.

Rust Doc comments on a function and a struct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The comments do not change how the program runs; the output only shows the struct and its area. Their value appears when you run cargo doc --open on your machine: you get a page for Rectangle with the description, the field docs and the example, in the same style as the standard library's own documentation.

Conventions for doc comments

The first paragraph is a one-sentence summary; it shows up in lists of items, so make it stand on its own. After that, community convention uses headings with fixed names, which readers know to look for:

  • # Examples shows how to use the item. Strongly recommended for every public item.
  • # Panics lists the situations in which the function panics.
  • # Errors says when a function returning Result returns Err, and which kinds.
  • # Safety is mandatory for unsafe functions: what the caller must guarantee.

Write in the third person present tense ("Returns the area", not "Return the area"), put names of items and values in backticks, and link to other items with square brackets: [`Rectangle`] becomes a link to that type. Intra-doc links like these are checked by rustdoc, so documentation does not silently point nowhere.

Module and crate docs: //!

//! documents the enclosing item instead of the next one. You put it at the top of a file or module to describe the module or the whole crate. A library's front page on docs.rs is the //! text at the top of src/lib.rs.

Rust Inner doc comments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Use /// when the comment comes before the thing it documents, and //! when it goes inside. If you get them confused the compiler gives an error such as E0753 ("expected outer doc comment", because inner doc comments can only appear before items), which tells you which one was wrong.

Doc comments are really attributes in disguise: /// text is shorthand for #[doc = " text"]. This is why a doc comment must be followed by something it can attach to. A /// comment at the end of a block, before nothing, is an error (E0585, "found a documentation comment that doesn't document anything").

Documentation tests

Every fenced code block in a doc comment is, by default, a doc test. When you run cargo test, rustdoc compiles each example as a tiny program and runs it. If the example does not compile or an assert! fails, the test fails. Documentation can therefore never go stale without somebody noticing, which is one of Rust's quietly great features.

Some details about doc tests:

  • Each block is wrapped in a fn main automatically; lines that start with # followed by a space are compiled but hidden in the rendered docs, handy for setup code.
  • A block can be marked ```ignore (not compiled), ```no_run (compiled, not run), ```should_panic or ```compile_fail.
  • The code uses your library the way a user would, through its public API, so the use lines you write in the example are also a check that the item is reachable.
Rust
// read-only: a library function with a doc test (needs cargo test)
/// Doubles a number.
///
/// ```
/// use mylib::double;
/// assert_eq!(double(4), 8);
/// ```
pub fn double(n: i32) -> i32 {
    n * 2
}

Our editor does not run rustdoc, but you can see the idea by making the example executable yourself: the program below repeats the doc-test assertion in main, so the example and the code are checked together.

Rust The idea behind doc tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Controlling lints with attributes

A lint is a check that reports suspicious code without being a hard error: an unused variable, unreachable code, a snake-case violation, an unsafe block without a comment. Each lint has a level:

  • allow: do not report it.
  • warn: report a warning, and keep compiling (the default for most lints).
  • deny: report an error and stop.
  • forbid: like deny, but nobody inside can override it with allow.

You set levels with attributes on an item, or #![...] at the top of a file to cover the whole crate. Here deny turns a normal warning into an error:

Rust deny turns a warning into an error (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

You will see error: unused variable: forgotten``, with a note "the lint level is defined here" that points at your #![deny(unused_variables)] line, and the suggestion to prefix the name with an underscore. This is how teams make CI fail on warnings. The command-line version is cargo clippy -- -D warnings or the environment variable RUSTFLAGS="-D warnings".

The opposite is allow, used to silence a lint on purpose. Put it on the smallest item possible, and add a comment saying why:

Rust allow on one item

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Without the attribute the compiler would warn function legacy_helper is never used. Dead code is a useful warning, so apply #[allow(dead_code)] narrowly rather than at the top of the file.

A few lints worth knowing

Lint What it catches Default
unused_variables A variable that is never read warn
dead_code A function, struct or field that is never used warn
unused_must_use Ignoring a Result or a #[must_use] value warn
non_snake_case A badly named function or variable warn
missing_docs A public item without documentation allow
unsafe_code Any use of unsafe allow

missing_docs is off by default; libraries often add #![warn(missing_docs)] to be reminded to document every public item. #[must_use] is a lint you attach to your own functions to say "ignoring the result is probably a bug". The standard library uses it on Result, so ignoring an error is a warning:

Rust An ignored Result (warning on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The program compiles and prints finished, but the compiler warns unused Result that must be used and notes that this Result may be an Err variant, which should be handled. Fix it by matching on the value, using ?, or writing let _ = parse_age("abc"); when you truly do not care. The error handling chapter shows how.

When you find a lint you disagree with, resist the urge to silence everything at the top of the crate. Fix the code, or add one narrow #[allow(...)] with a comment. Run rustc -W help (or cargo clippy) to see what lints exist, and use Clippy and fmt to enforce a consistent standard.

Generating the docs

On your own machine, cargo doc --open builds the HTML for your crate and all of its dependencies and opens it in the browser. It includes search, links between types, and the source code view. When you publish a library to crates.io, docs.rs builds and hosts the same documentation automatically for every version, so well-written doc comments are the public face of your crate.

Terminal
# read-only commands for your own computer
cargo doc --open                  # build and view docs
cargo doc --no-deps               # only your crate, faster
cargo test --doc                  # run only the documentation tests

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which comment documents the item that comes right after it?

    Three slashes make an outer doc comment that attaches to the next item. //! is an inner doc comment for the enclosing item (a file, module or crate), and // is an ordinary comment.
  2. 2. What is special about block comments in Rust?

    Rust block comments nest. The inner */ closes only the inner comment, which makes it safe to comment out code that already contains block comments.
  3. 3. What happens to a fenced code block inside a /// comment when you run cargo test?

    rustdoc turns each code block into a small test program. A block can opt out with ignore, no_run and similar tags.
  4. 4. You write #![deny(unused_variables)] at the top of a crate and leave a variable unused. What does the compiler do?

    deny raises the lint level to error. The build stops until you use the variable, rename it with a leading underscore or lower the lint level.
  5. 5. What is the best use of an ordinary comment?

    Code already says what it does. Comments earn their place by recording intent, constraints and surprises that the code cannot express.

Summary

  • // makes a line comment; /* ... */ makes a block comment, and block comments nest. Comments should explain why, not what.
  • /// documents the next item; //! documents the enclosing item (a module or the whole crate). Both accept Markdown.
  • Conventional doc headings are # Examples, # Panics, # Errors and # Safety.
  • Code blocks in doc comments are tested by cargo test, so examples stay correct; cargo doc --open renders the documentation, and docs.rs hosts it for published crates.
  • Lint levels are allow, warn, deny and forbid, set with #[...] on an item or #![...] for a crate. Use narrow allows with a reason, and deny(warnings) or -D warnings in CI.
  • #[must_use] (used by Result) warns when a value that should be handled is ignored.

Next: Printing with println! and format!