Sub topic 8
Hiding setup lines with #
A doc test is a complete program, but a reader of your documentation only needs to see the part that teaches something. This chapter covers the # prefix, which lets a line be compiled without being displayed. It also covers where the feature goes wrong and how to decide what to hide.
This chapter assumes you can write /// comments with fenced examples and run cargo test --doc. Both were covered in earlier chapters.
The problem hidden lines solve
An example that compiles often needs scaffolding. It needs imports, a value to work on, or a helper type. If you show all of it, the one line that demonstrates your API gets lost.
Here is the body of an example, with the fence lines of the doc comment left out:
use std::collections::HashMap;
let mut stock = HashMap::new();
stock.insert("apple", 3);
let count = stock.get("apple").copied().unwrap_or(0);
assert_eq!(count, 3);Only the last two lines are the point. The first three are setup. Prefix them with # and rustdoc still compiles them but leaves them out of the HTML:
# use std::collections::HashMap;
# let mut stock = HashMap::new();
# stock.insert("apple", 3);
let count = stock.get("apple").copied().unwrap_or(0);
assert_eq!(count, 3);The rendered page shows two lines. The test runs all five.
The syntax rules
A line is hidden when its first non-whitespace content is a # followed by a space, or a # alone on the line. The rules are small, but each one has an edge case.
| Line in the example | Result in rendered docs | Compiled? |
|---|---|---|
| `# let x = 1;` | hidden | yes, as `let x = 1;` |
| `#` | hidden (blank line) | yes, as an empty line |
| `## not hidden` | shown as `# not hidden` | yes, as `# not hidden` |
| `#[derive(Debug)]` | shown as written | yes |
| `#![allow(unused)]` | shown as written | yes |
Attributes such as #[derive(Debug)] are not hidden, because the # is followed by [ and not a space. You never need to escape them. To hide an attribute, put a space after the # and write # #[derive(Debug)]. The first # is stripped and the attribute remains.
Indentation before the # is allowed. This matters inside blocks, because you can hide a single line in the middle of an indented body and keep the surrounding structure visible.
What rustdoc builds from your example
Rustdoc removes the # prefix from each hidden line and keeps the line in the program. If your example has no fn main, rustdoc wraps all of it, hidden and visible, in one. The example from the previous section becomes roughly this program:
fn main() {
use std::collections::HashMap;
let mut stock = HashMap::new();
stock.insert("apple", 3);
let count = stock.get("apple").copied().unwrap_or(0);
assert_eq!(count, 3);
}Rustdoc writes this program to a temporary file, compiles it as its own crate, links it against your library, and runs it. The doc test passes if it compiles and exits without panicking.
Typical things to hide
Four kinds of lines are usually worth hiding.
- Imports that are not the topic. If the page documents
parse_port, a reader needs to see where it comes from, so keep thatuse. Hide imports ofstdtypes used only to build inputs. - Fixture values. A
Vec, a config struct, or a file path that exists only so the call has something to work on. - Helper items. A small type or trait implementation the example needs to compile.
- The closing expression for
?. An example that uses?must end in an explicitResult. The previous chapter's pattern hides that last line:
let port = parse_port("8080")?;
assert_eq!(port, 8080);
# Ok::<(), std::num::ParseIntError>(())Hidden helper items are easy to forget. This example defines a type that only exists for the demonstration:
# struct Celsius(f64);
# impl Celsius {
# fn to_fahrenheit(&self) -> f64 { self.0 * 9.0 / 5.0 + 32.0 }
# }
let boiling = Celsius(100.0);
assert_eq!(boiling.to_fahrenheit(), 212.0);Each line of the helper needs its own # . There is no block form.
What not to hide
Hidden lines are invisible in the rendered docs, so hide only what the reader can ignore. Three cases need care.
- Anything the reader must copy to make the code work. If a
useline is needed and is not obvious, a reader who pastes the visible lines gets a compile error. - Values that explain the result. If
assert_eq!(total, 42)depends on a hiddenlet prices = [20, 22];, the reader cannot see why 42 is right. Show the input. - Behavior you are documenting. Hide scaffolding, not the call that produces the result. A hidden call to your API means the example teaches nothing.
Edge cases and gotchas
Hidden-line processing applies only to Rust blocks
The # rule is applied to code blocks that rustdoc treats as Rust. That includes blocks with no language and blocks with attributes such as no_run or should_panic. A block marked text, toml, or sh is displayed verbatim, so a # comment in a shell script stays visible. The text blocks in this chapter work the same way.
Strings that contain lines starting with `#`
A multi-line string literal in a Rust example can contain a line that begins with #, for example a TOML heading or a Markdown title. Rustdoc does not parse Rust syntax when it hides lines, so it hides that line even though it is inside a string. Escape it with ##:
let config = r#"
## [server]
port = 8080
"#;
assert!(config.contains("port"));The ## line is compiled as # [server], which keeps the TOML heading intact. Forgetting the second # leaves the string without the heading and changes your test.
Error line numbers include hidden lines
When a doc test fails, the compiler reports line numbers in the generated program. Hidden lines count, and rustdoc also adds a few lines around your code. Read the printed source in the failure output and match it to your example by content, not by position. The failure header names the file and the line where the code block starts, which gets you to the right comment.
Hidden lines are still part of the test
Hiding a line does not make it optional. If a hidden use is unused, you may get warnings, and a hidden fixture can fail and break the test even though the reader never sees it. Rustdoc allows unused lints by default in doc tests, so unused setup does not fail the build. You can opt in to stricter checking with #![deny(warnings)] in the example, but doing so makes the example brittle across compiler versions.
Don't hide your own item's path unless the crate is obvious
Doc tests can use only your public API, and they refer to the crate by name. A hidden # use mycrate::parse_port; is a common choice for functions that sit at the crate root, where the page already makes the origin clear. For items in deeper modules, show the use, because the module path is real information.
Checking your work
Run the doc tests for the crate to confirm that hidden setup compiles:
cargo test --docThen build the HTML and open the page to confirm that the visible part reads well on its own:
cargo doc --no-deps --openDo both. The first checks that the hidden lines are correct. The second checks that the visible lines are enough.
Exercise
An example has these lines in a Rust code block, and the rendered page shows only the last two. Which line forms hide lines, and what happens to #[derive(Debug)] if it appears in the example?
# use std::collections::BTreeMap;
# let mut m = BTreeMap::new();
m.insert(1, "one");
assert_eq!(m.len(), 1);
Show answer
A line is hidden when it starts with # followed by a space, or is a lone #. Here the first two lines are hidden but still compiled, so the program runs with the use and the let. A line like #[derive(Debug)] is not hidden, because # is followed by [ and not a space. It is shown as written and compiled as normal. To hide it you would write # #[derive(Debug)].
Exercise
Your example contains a multi-line string with a line # Title that should appear in the string at run time. Without changes, the test fails because the line is missing. Why does this happen, and how do you fix it?
Show answer
Rustdoc hides lines that start with # without parsing Rust, so it removes the line from the generated program even though it is inside a string literal. Write ## Title instead. Rustdoc compiles that line as # Title, and the string contains the heading.