@@ -200,15 +200,15 @@ Because these kinds of situations are relatively rare, use panics sparingly.
200200# Upgrading failures to panics
201201
202202In 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.
206206
207207If we don't want to handle this error, and would rather just abort the program,
208208we can use the ` unwrap() ` method:
209209
210210``` {rust,ignore}
211- io::stdin().read_line().unwrap();
211+ io::stdin().read_line(&mut buffer ).unwrap();
212212```
213213
214214` unwrap() ` will ` panic! ` if the ` Option ` is ` None ` . This basically says "Give
@@ -219,12 +219,13 @@ shorter. Sometimes, just crashing is appropriate.
219219There's another way of doing this that's a bit nicer than ` unwrap() ` :
220220
221221``` {rust,ignore}
222- let input = io::stdin().read_line()
222+ let mut buffer = String::new();
223+ let input = io::stdin().read_line(&mut buffer)
223224 .ok()
224225 .expect("Failed to read line");
225226```
226227
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
228229thing as ` unwrap() ` , but takes a message. This message is passed along to the
229230underlying ` panic! ` , providing a better error message if the code errors.
230231
0 commit comments