diff options
| author | bors <bors@rust-lang.org> | 2014-03-12 15:07:06 -0700 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2014-03-12 15:07:06 -0700 |
| commit | 4d64441bcb820cf35d3e39dde8514c46765a12a6 (patch) | |
| tree | 541bf3eb9112d8e40475b90f6da342980bbde7f8 /src/libstd/io | |
| parent | 3316a0e6b2ad9352bab58e7c046ef3d212411d82 (diff) | |
| parent | 3f2434eee3f7fa72bf7a8693aef3932d563cf8d5 (diff) | |
| download | rust-4d64441bcb820cf35d3e39dde8514c46765a12a6.tar.gz rust-4d64441bcb820cf35d3e39dde8514c46765a12a6.zip | |
auto merge of #12848 : alexcrichton/rust/rollup, r=alexcrichton
Diffstat (limited to 'src/libstd/io')
| -rw-r--r-- | src/libstd/io/mod.rs | 34 | ||||
| -rw-r--r-- | src/libstd/io/test.rs | 1 |
2 files changed, 34 insertions, 1 deletions
diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index 7a18f24140a..1c10c7b61c3 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -172,6 +172,40 @@ need to inspect or unwrap the `IoResult<File>` and we simply call `write_line` on it. If `new` returned an `Err(..)` then the followup call to `write_line` will also return an error. +## `try!` + +Explicit pattern matching on `IoResult`s can get quite verbose, especially +when performing many I/O operations. Some examples (like those above) are +alleviated with extra methods implemented on `IoResult`, but others have more +complex interdependencies among each I/O operation. + +The `try!` macro from `std::macros` is provided as a method of early-return +inside `Result`-returning functions. It expands to an early-return on `Err` +and otherwise unwraps the contained `Ok` value. + +If you wanted to read several `u32`s from a file and return their product: + +```rust +use std::io::{File, IoResult}; + +fn file_product(p: &Path) -> IoResult<u32> { + let mut f = File::open(p); + let x1 = try!(f.read_le_u32()); + let x2 = try!(f.read_le_u32()); + + Ok(x1 * x2) +} + +match file_product(&Path::new("numbers.bin")) { + Ok(x) => println!("{}", x), + Err(e) => println!("Failed to read numbers!") +} +``` + +With `try!` in `file_product`, each `read_le_u32` need not be directly +concerned with error handling; instead its caller is responsible for +responding to errors that may occur while attempting to read the numbers. + */ #[deny(unused_must_use)]; diff --git a/src/libstd/io/test.rs b/src/libstd/io/test.rs index d6f7f58f01c..73d52654ebf 100644 --- a/src/libstd/io/test.rs +++ b/src/libstd/io/test.rs @@ -150,7 +150,6 @@ mod darwin_fd_limit { rlim_cur: rlim_t, rlim_max: rlim_t } - #[nolink] extern { // name probably doesn't need to be mut, but the C function doesn't specify const fn sysctl(name: *mut libc::c_int, namelen: libc::c_uint, |
