@@ -172,6 +172,40 @@ need to inspect or unwrap the `IoResult<File>` and we simply call `write_line`
172
172
on it. If `new` returned an `Err(..)` then the followup call to `write_line`
173
173
will also return an error.
174
174
175
+ ## `try!`
176
+
177
+ Explicit pattern matching on `IoResult`s can get quite verbose, especially
178
+ when performing many I/O operations. Some examples (like those above) are
179
+ alleviated with extra methods implemented on `IoResult`, but others have more
180
+ complex interdependencies among each I/O operation.
181
+
182
+ The `try!` macro from `std::macros` is provided as a method of early-return
183
+ inside `Result`-returning functions. It expands to an early-return on `Err`
184
+ and otherwise unwraps the contained `Ok` value.
185
+
186
+ If you wanted to read several `u32`s from a file and return their product:
187
+
188
+ ```rust
189
+ use std::io::{File, IoResult};
190
+
191
+ fn file_product(p: &Path) -> IoResult<u32> {
192
+ let mut f = File::open(p);
193
+ let x1 = try!(f.read_le_u32());
194
+ let x2 = try!(f.read_le_u32());
195
+
196
+ Ok(x1 * x2)
197
+ }
198
+
199
+ match file_product(&Path::new("numbers.bin")) {
200
+ Ok(x) => println!("{}", x),
201
+ Err(e) => println!("Failed to read numbers!")
202
+ }
203
+ ```
204
+
205
+ With `try!` in `file_product`, each `read_le_u32` need not be directly
206
+ concerned with error handling; instead its caller is responsible for
207
+ responding to errors that may occur while attempting to read the numbers.
208
+
175
209
*/
176
210
177
211
#[ deny( unused_must_use) ] ;
0 commit comments