Skip to content

Commit 63885f7

Browse files
committed
Update rustdoc book to suggest using Termination trait instead of hidden ‘foo’ function
1 parent f33db06 commit 63885f7

File tree

1 file changed

+29
-11
lines changed

1 file changed

+29
-11
lines changed

src/doc/rustdoc/src/documentation-tests.md

Lines changed: 29 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -168,37 +168,55 @@ By repeating all parts of the example, you can ensure that your example still
168168
compiles, while only showing the parts that are relevant to that part of your
169169
explanation.
170170
171-
Another case where the use of `#` is handy is when you want to ignore
172-
error handling. Lets say you want the following,
171+
172+
## Using `?` in doc tests
173+
174+
A complete error handling is often not useful in your example, as it would add
175+
significant amounts of boilerplate code. Instead, you may want the following:
173176
174177
```ignore
178+
/// ```
175179
/// use std::io;
176180
/// let mut input = String::new();
177181
/// io::stdin().read_line(&mut input)?;
182+
/// ```
178183
```
179184

180-
The problem is that `?` returns a `Result<T, E>` and test functions
181-
don't return anything so this will give a mismatched types error.
185+
The problem is that `?` returns a `Result<T, E>` and test functions don't
186+
return anything, so this will give a mismatched types error.
187+
188+
You can get around this limitation by manually adding a `main` that returns
189+
`Result<T, E>`, because `Result<T, E>` implements the `Termination` trait:
182190

183191
```ignore
184192
/// A doc test using ?
185193
///
186194
/// ```
187195
/// use std::io;
188-
/// # fn foo() -> io::Result<()> {
196+
///
197+
/// fn main() -> io::Result<()> {
198+
/// let mut input = String::new();
199+
/// io::stdin().read_line(&mut input)?;
200+
/// Ok(())
201+
/// }
202+
/// ```
203+
```
204+
205+
Together with the `# ` from the section above, you arrive at a solution that
206+
appears to the reader as the initial idea but works with doc tests:
207+
208+
```ignore
209+
/// ```
210+
/// use std::io;
211+
/// # fn main() -> io::Result<()> {
189212
/// let mut input = String::new();
190213
/// io::stdin().read_line(&mut input)?;
191214
/// # Ok(())
192215
/// # }
193216
/// ```
194-
# fn foo() {}
195217
```
196218

197-
You can get around this by wrapping the code in a function. This catches
198-
and swallows the `Result<T, E>` when running tests on the docs. This
199-
pattern appears regularly in the standard library.
200-
201-
### Documenting macros
219+
## Documenting macros
202220

203221
Here’s an example of documenting a macro:
204222

0 commit comments

Comments
 (0)