Skip to content

Commit 735c81b

Browse files
tarialexcrichton
authored andcommitted
---
yaml --- r: 105893 b: refs/heads/auto c: 207ebf1 h: refs/heads/master i: 105891: b894a76 v: v3
1 parent 3224fa4 commit 735c81b

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
@@ -13,7 +13,7 @@ refs/heads/try3: 9387340aab40a73e8424c48fd42f0c521a4875c0
1313
refs/tags/release-0.3.1: 495bae036dfe5ec6ceafd3312b4dca48741e845b
1414
refs/tags/release-0.4: e828ea2080499553b97dfe33b3f4d472b4562ad7
1515
refs/tags/release-0.5: 7e3bcfbf21278251ee936ad53e92e9b719702d73
16-
refs/heads/auto: 91bed14ca8085887a26d029d785d853ad2587718
16+
refs/heads/auto: 207ebf13f12d8fa4449d66cd86407de03f264667
1717
refs/heads/servo: af82457af293e2a842ba6b7759b70288da276167
1818
refs/tags/release-0.6: b4ebcfa1812664df5e142f0134a5faea3918544c
1919
refs/tags/0.1: b19db808c2793fe2976759b85a355c3ad8c8b336

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