Skip to content

Commit bda8515

Browse files
committed
auto merge of #12819 : tari/rust/io-docs-try, r=alexcrichton
std::macros::try says to refer to std::io for more information. This patch adds an example of try! when doing I/O. Redo of #12817 following some fumbling with git.
2 parents a0f20f0 + b56b046 commit bda8515

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

src/libstd/io/mod.rs

+34
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,40 @@ need to inspect or unwrap the `IoResult<File>` and we simply call `write_line`
172172
on it. If `new` returned an `Err(..)` then the followup call to `write_line`
173173
will also return an error.
174174
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+
175209
*/
176210

177211
#[deny(unused_must_use)];

0 commit comments

Comments
 (0)