@@ -168,37 +168,55 @@ By repeating all parts of the example, you can ensure that your example still
168
168
compiles, while only showing the parts that are relevant to that part of your
169
169
explanation.
170
170
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:
173
176
174
177
```ignore
178
+ /// ```
175
179
/// use std::io;
176
180
/// let mut input = String::new();
177
181
/// io::stdin().read_line(&mut input)?;
182
+ /// ```
178
183
```
179
184
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:
182
190
183
191
``` ignore
184
192
/// A doc test using ?
185
193
///
186
194
/// ```
187
195
/// 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<()> {
189
212
/// let mut input = String::new();
190
213
/// io::stdin().read_line(&mut input)?;
191
214
/// # Ok(())
192
215
/// # }
193
216
/// ```
194
- # fn foo() {}
195
217
```
196
218
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
202
220
203
221
Here’s an example of documenting a macro:
204
222
0 commit comments