Skip to content

Commit f7efe36

Browse files
tarialexcrichton
authored andcommitted
---
yaml --- r: 149893 b: refs/heads/try2 c: 207ebf1 h: refs/heads/master i: 149891: fc1aaf4 v: v3
1 parent 2ed189c commit f7efe36

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
@@ -5,7 +5,7 @@ refs/heads/snap-stage3: 78a7676898d9f80ab540c6df5d4c9ce35bb50463
55
refs/heads/try: 519addf6277dbafccbb4159db4b710c37eaa2ec5
66
refs/tags/release-0.1: 1f5c5126e96c79d22cb7862f75304136e204f105
77
refs/heads/ndm: f3868061cd7988080c30d6d5bf352a5a5fe2460b
8-
refs/heads/try2: 91bed14ca8085887a26d029d785d853ad2587718
8+
refs/heads/try2: 207ebf13f12d8fa4449d66cd86407de03f264667
99
refs/heads/dist-snap: ba4081a5a8573875fed17545846f6f6902c8ba8d
1010
refs/tags/release-0.2: c870d2dffb391e14efb05aa27898f1f6333a9596
1111
refs/tags/release-0.3: b5f0d0f648d9a6153664837026ba1be43d3e2503

branches/try2/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)