@@ -170,37 +170,56 @@ By repeating all parts of the example, you can ensure that your example still
170
170
compiles, while only showing the parts that are relevant to that part of your
171
171
explanation.
172
172
173
- Another case where the use of `#` is handy is when you want to ignore
174
- error handling. Lets say you want the following,
173
+
174
+ ## Using `?` in doc tests
175
+
176
+ When writing an example, it is rarely useful to include a complete error
177
+ handling, as it would add significant amounts of boilerplate code. Instead, you
178
+ may want the following:
175
179
176
180
```ignore
181
+ /// ```
177
182
/// use std::io;
178
183
/// let mut input = String::new();
179
184
/// io::stdin().read_line(&mut input)?;
185
+ /// ```
180
186
```
181
187
182
- The problem is that ` ? ` returns a ` Result<T, E> ` and test functions
183
- don't return anything so this will give a mismatched types error.
188
+ The problem is that ` ? ` returns a ` Result<T, E> ` and test functions don't
189
+ return anything, so this will give a mismatched types error.
190
+
191
+ You can get around this limitation by manually adding a ` main ` that returns
192
+ ` Result<T, E> ` , because ` Result<T, E> ` implements the ` Termination ` trait:
184
193
185
194
``` ignore
186
195
/// A doc test using ?
187
196
///
188
197
/// ```
189
198
/// use std::io;
190
- /// # fn foo() -> io::Result<()> {
199
+ ///
200
+ /// fn main() -> io::Result<()> {
201
+ /// let mut input = String::new();
202
+ /// io::stdin().read_line(&mut input)?;
203
+ /// Ok(())
204
+ /// }
205
+ /// ```
206
+ ```
207
+
208
+ Together with the ` # ` from the section above, you arrive at a solution that
209
+ appears to the reader as the initial idea but works with doc tests:
210
+
211
+ ``` ignore
212
+ /// ```
213
+ /// use std::io;
214
+ /// # fn main() -> io::Result<()> {
191
215
/// let mut input = String::new();
192
216
/// io::stdin().read_line(&mut input)?;
193
217
/// # Ok(())
194
218
/// # }
195
219
/// ```
196
- # fn foo() {}
197
220
```
198
221
199
- You can get around this by wrapping the code in a function. This catches
200
- and swallows the ` Result<T, E> ` when running tests on the docs. This
201
- pattern appears regularly in the standard library.
202
-
203
- ### Documenting macros
222
+ ## Documenting macros
204
223
205
224
Here’s an example of documenting a macro:
206
225
0 commit comments