@@ -200,15 +200,15 @@ Because these kinds of situations are relatively rare, use panics sparingly.
200
200
# Upgrading failures to panics
201
201
202
202
In certain circumstances, even though a function may fail, we may want to treat
203
- it as a panic instead. For example, ` io::stdin().read_line() ` returns an
204
- ` IoResult<String >` , a form of ` Result ` , when there is an error reading the
205
- line. This allows us to handle and possibly recover from this sort of error.
203
+ it as a panic instead. For example, ` io::stdin().read_line(&mut buffer ) ` returns
204
+ an ` Result<usize >` , when there is an error reading the line. This allows us to
205
+ handle and possibly recover from error.
206
206
207
207
If we don't want to handle this error, and would rather just abort the program,
208
208
we can use the ` unwrap() ` method:
209
209
210
210
``` {rust,ignore}
211
- io::stdin().read_line().unwrap();
211
+ io::stdin().read_line(&mut buffer ).unwrap();
212
212
```
213
213
214
214
` unwrap() ` will ` panic! ` if the ` Option ` is ` None ` . This basically says "Give
@@ -219,12 +219,13 @@ shorter. Sometimes, just crashing is appropriate.
219
219
There's another way of doing this that's a bit nicer than ` unwrap() ` :
220
220
221
221
``` {rust,ignore}
222
- let input = io::stdin().read_line()
222
+ let mut buffer = String::new();
223
+ let input = io::stdin().read_line(&mut buffer)
223
224
.ok()
224
225
.expect("Failed to read line");
225
226
```
226
227
227
- ` ok() ` converts the ` IoResult ` into an ` Option ` , and ` expect() ` does the same
228
+ ` ok() ` converts the ` Result ` into an ` Option ` , and ` expect() ` does the same
228
229
thing as ` unwrap() ` , but takes a message. This message is passed along to the
229
230
underlying ` panic! ` , providing a better error message if the code errors.
230
231
0 commit comments