3 `rustdoc` supports executing your documentation examples as tests. This makes sure
4 that your tests are up to date and working.
6 The basic idea is this:
16 The triple backticks start and end code blocks. If this were in a file named `foo.rs`,
17 running `rustdoc --test foo.rs` will extract this example, and then run it as a test.
19 Please note that by default, if no language is set for the block code, `rustdoc`
20 assumes it is `Rust` code. So the following:
28 is strictly equivalent to:
36 There's some subtlety though! Read on for more details.
38 ## Passing or failing a doctest
40 Like regular unit tests, regular doctests are considered to "pass"
41 if they compile and run without panicking.
42 So if you want to demonstrate that some computation gives a certain result,
43 the `assert!` family of macros works the same as other Rust code:
48 assert_eq!(foo, "foo");
51 This way, if the computation ever returns something different,
52 the code panics and the doctest fails.
54 ## Pre-processing examples
56 In the example above, you'll note something strange: there's no `main`
57 function! Forcing you to write `main` for every example, no matter how small,
58 adds friction. So `rustdoc` processes your examples slightly before
59 running them. Here's the full algorithm rustdoc uses to preprocess examples:
61 1. Some common `allow` attributes are inserted, including
62 `unused_variables`, `unused_assignments`, `unused_mut`,
63 `unused_attributes`, and `dead_code`. Small examples often trigger
65 2. Any attributes specified with `#![doc(test(attr(...)))]` are added.
66 3. Any leading `#![foo]` attributes are left intact as crate attributes.
67 4. If the example does not contain `extern crate`, and
68 `#![doc(test(no_crate_inject))]` was not specified, then `extern crate
69 <mycrate>;` is inserted (note the lack of `#[macro_use]`).
70 5. Finally, if the example does not contain `fn main`, the remainder of the
71 text is wrapped in `fn main() { your_code }`.
73 For more about that caveat in rule 4, see "Documenting Macros" below.
75 ## Hiding portions of the example
77 Sometimes, you need some setup code, or other things that would distract
78 from your example, but are important to make the tests work. Consider
79 an example block that looks like this:
82 /// /// Some documentation.
83 /// # fn foo() {} // this function will be hidden
84 /// println!("Hello, World!");
87 It will render like this:
90 /// Some documentation.
92 println!("Hello, World!");
95 Yes, that's right: you can add lines that start with `# `, and they will
96 be hidden from the output, but will be used when compiling your code. You
97 can use this to your advantage. In this case, documentation comments need
98 to apply to some kind of function, so if I want to show you just a
99 documentation comment, I need to add a little function definition below
100 it. At the same time, it's only there to satisfy the compiler, so hiding
101 it makes the example more clear. You can use this technique to explain
102 longer examples in detail, while still preserving the testability of your
105 For example, imagine that we wanted to document this code:
110 println!("{}", x + y);
113 We might want the documentation to end up looking like this:
115 > First, we set `x` to five:
120 > # println!("{}", x + y);
123 > Next, we set `y` to six:
128 > # println!("{}", x + y);
131 > Finally, we print the sum of `x` and `y`:
136 > println!("{}", x + y);
139 To keep each code block testable, we want the whole program in each block, but
140 we don't want the reader to see every line every time. Here's what we put in
144 First, we set `x` to five:
149 # println!("{}", x + y);
152 Next, we set `y` to six:
157 # println!("{}", x + y);
160 Finally, we print the sum of `x` and `y`:
165 println!("{}", x + y);
169 By repeating all parts of the example, you can ensure that your example still
170 compiles, while only showing the parts that are relevant to that part of your
173 The `#`-hiding of lines can be prevented by using two consecutive hashes
174 `##`. This only needs to be done with with the first `#` which would've
175 otherwise caused hiding. If we have a string literal like the following,
176 which has a line that starts with a `#`:
183 We can document it by escaping the initial `#`:
191 ## Using `?` in doc tests
193 When writing an example, it is rarely useful to include a complete error
194 handling, as it would add significant amounts of boilerplate code. Instead, you
195 may want the following:
200 /// let mut input = String::new();
201 /// io::stdin().read_line(&mut input)?;
205 The problem is that `?` returns a `Result<T, E>` and test functions don't
206 return anything, so this will give a mismatched types error.
208 You can get around this limitation by manually adding a `main` that returns
209 `Result<T, E>`, because `Result<T, E>` implements the `Termination` trait:
212 /// A doc test using ?
217 /// fn main() -> io::Result<()> {
218 /// let mut input = String::new();
219 /// io::stdin().read_line(&mut input)?;
225 Together with the `# ` from the section above, you arrive at a solution that
226 appears to the reader as the initial idea but works with doc tests:
231 /// # fn main() -> io::Result<()> {
232 /// let mut input = String::new();
233 /// io::stdin().read_line(&mut input)?;
239 ## Documenting macros
241 Here’s an example of documenting a macro:
244 /// Panic with a given message unless an expression evaluates to true.
249 /// # #[macro_use] extern crate foo;
251 /// panic_unless!(1 + 1 == 2, “Math is broken.”);
256 /// # #[macro_use] extern crate foo;
258 /// panic_unless!(true == false, “I’m broken.”);
262 macro_rules! panic_unless {
263 ($condition:expr, $($rest:expr),+) => ({ if ! $condition { panic!($($rest),+); } });
268 You’ll note three things: we need to add our own `extern crate` line, so that
269 we can add the `#[macro_use]` attribute. Second, we’ll need to add our own
270 `main()` as well (for reasons discussed above). Finally, a judicious use of
271 `#` to comment out those two things, so they don’t show up in the output.
275 There are a few annotations that are useful to help `rustdoc` do the right
276 thing when testing your code:
285 The `ignore` directive tells Rust to ignore your code. This is almost never
286 what you want, as it's the most generic. Instead, consider annotating it
287 with `text` if it's not code, or using `#`s to get a working example that
288 only shows the part you care about.
297 `should_panic` tells `rustdoc` that the code should compile correctly, but
298 not actually pass as a test.
303 /// println!("Hello, world");
309 The `no_run` attribute will compile your code, but not run it. This is
310 important for examples such as "Here's how to retrieve a web page,"
311 which you would want to ensure compiles, but might be run in a test
312 environment that has no network access.
317 /// x += 2; // shouldn't compile!
321 `compile_fail` tells `rustdoc` that the compilation should fail. If it
322 compiles, then the test will fail. However please note that code failing
323 with the current Rust release may work in a future release, as new features
328 The *exact* syntax for code blocks, including the edge cases, can be found
329 in the [Fenced Code Blocks](https://spec.commonmark.org/0.28/#fenced-code-blocks)
330 section of the CommonMark specification.
332 Rustdoc also accepts *indented* code blocks as an alternative to fenced
333 code blocks: instead of surrounding your code with three backticks, you
334 can indent each line by four or more spaces.
338 assert_eq!(foo, "foo");
341 These, too, are documented in the CommonMark specification, in the
342 [Indented Code Blocks](https://spec.commonmark.org/0.28/#indented-code-blocks)
345 However, it's preferable to use fenced code blocks over indented code blocks.
346 Not only are fenced code blocks considered more idiomatic for Rust code,
347 but there is no way to use directives such as `ignore` or `should_panic` with
348 indented code blocks.