Skip to content

Commit 80402f0

Browse files
tarialexcrichton
authored andcommitted
---
yaml --- r: 105275 b: refs/heads/master c: 207ebf1 h: refs/heads/master i: 105273: e5ec662 105271: 48ce8ac v: v3
1 parent 697f47d commit 80402f0

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

[refs]

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
---
2-
refs/heads/master: 91bed14ca8085887a26d029d785d853ad2587718
2+
refs/heads/master: 207ebf13f12d8fa4449d66cd86407de03f264667
33
refs/heads/snap-stage1: e33de59e47c5076a89eadeb38f4934f58a3618a6
44
refs/heads/snap-stage3: b8601a3d8b91ad3b653d143307611f2f5c75617e
55
refs/heads/try: db814977d07bd798feb24f6b74c00800ef458a13

trunk/src/libstd/io/mod.rs

Lines changed: 34 additions & 0 deletions
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)