]> git.lizzy.rs Git - rust.git/blob - src/libstd/result.rs
core: Add unwrap()/unwrap_err() methods to Result
[rust.git] / src / libstd / result.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Error handling with the `Result` type
12 //!
13 //! `Result<T>` is the type used for returning and propagating
14 //! errors. It is an enum with the variants, `Ok(T)`, representing
15 //! success and containing a value, and `Err(E)`, representing error
16 //! and containing an error value.
17 //!
18 //! ~~~
19 //! enum Result<T, E> {
20 //!    Ok(T),
21 //!    Err(E)
22 //! }
23 //! ~~~
24 //!
25 //! Functions return `Result` whenever errors are expected and
26 //! recoverable. In the `std` crate `Result` is most prominently used
27 //! for [I/O](../io/index.html).
28 //!
29 //! A simple function returning `Result` might be
30 //! defined and used like so:
31 //!
32 //! ~~~
33 //! #[deriving(Show)]
34 //! enum Version { Version1, Version2 }
35 //!
36 //! fn parse_version(header: &[u8]) -> Result<Version, &'static str> {
37 //!     if header.len() < 1 {
38 //!         return Err("invalid header length");
39 //!     }
40 //!     match header[0] {
41 //!         1 => Ok(Version1),
42 //!         2 => Ok(Version2),
43 //!         _ => Err("invalid version")
44 //!     }
45 //! }
46 //!
47 //! let version = parse_version(&[1, 2, 3, 4]);
48 //! match version {
49 //!     Ok(v) => {
50 //!         println!("working with version: {}", v);
51 //!     }
52 //!     Err(e) => {
53 //!         println!("error parsing header: {}", e);
54 //!     }
55 //! }
56 //! ~~~
57 //!
58 //! Pattern matching on `Result`s is clear and straightforward for
59 //! simple cases, but `Result` comes with some convenience methods
60 //! that make working it more succinct.
61 //!
62 //! ~~~
63 //! let good_result: Result<int, int> = Ok(10);
64 //! let bad_result: Result<int, int> = Err(10);
65 //!
66 //! // The `is_ok` and `is_err` methods do what they say.
67 //! assert!(good_result.is_ok() && !good_result.is_err());
68 //! assert!(bad_result.is_err() && !bad_result.is_ok());
69 //!
70 //! // `map` consumes the `Result` and produces another.
71 //! let good_result: Result<int, int> = good_result.map(|i| i + 1);
72 //! let bad_result: Result<int, int> = bad_result.map(|i| i - 1);
73 //!
74 //! // Use `and_then` to continue the computation.
75 //! let good_result: Result<bool, int> = good_result.and_then(|i| Ok(i == 11));
76 //!
77 //! // Use `or_else` to handle the error.
78 //! let bad_result: Result<int, int> = bad_result.or_else(|i| Ok(11));
79 //!
80 //! // Consume the result and return the contents with `unwrap`.
81 //! let final_awesome_result = good_result.ok().unwrap();
82 //! ~~~
83 //!
84 //! # Results must be used
85 //!
86 //! A common problem with using return values to indicate errors is
87 //! that it is easy to ignore the return value, thus failing to handle
88 //! the error. Result is annotated with the #[must_use] attribute,
89 //! which will cause the compiler to issue a warning when a Result
90 //! value is ignored. This makes `Result` especially useful with
91 //! functions that may encounter errors but don't otherwise return a
92 //! useful value.
93 //!
94 //! Consider the `write_line` method defined for I/O types
95 //! by the [`Writer`](../io/trait.Writer.html) trait:
96 //!
97 //! ~~~
98 //! use std::io::IoError;
99 //!
100 //! trait Writer {
101 //!     fn write_line(&mut self, s: &str) -> Result<(), IoError>;
102 //! }
103 //! ~~~
104 //!
105 //! *Note: The actual definition of `Writer` uses `IoResult`, which
106 //! is just a synonym for `Result<T, IoError>`.*
107 //!
108 //! This method doesn`t produce a value, but the write may
109 //! fail. It's crucial to handle the error case, and *not* write
110 //! something like this:
111 //!
112 //! ~~~ignore
113 //! use std::io::{File, Open, Write};
114 //!
115 //! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
116 //! // If `write_line` errors, then we'll never know, because the return
117 //! // value is ignored.
118 //! file.write_line("important message");
119 //! drop(file);
120 //! ~~~
121 //!
122 //! If you *do* write that in Rust, the compiler will by give you a
123 //! warning (by default, controlled by the `unused_must_use` lint).
124 //!
125 //! You might instead, if you don't want to handle the error, simply
126 //! fail, by converting to an `Option` with `ok`, then asserting
127 //! success with `expect`. This will fail if the write fails, proving
128 //! a marginally useful message indicating why:
129 //!
130 //! ~~~no_run
131 //! use std::io::{File, Open, Write};
132 //!
133 //! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
134 //! file.write_line("important message").ok().expect("failed to write message");
135 //! drop(file);
136 //! ~~~
137 //!
138 //! You might also simply assert success:
139 //!
140 //! ~~~no_run
141 //! # use std::io::{File, Open, Write};
142 //!
143 //! # let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
144 //! assert!(file.write_line("important message").is_ok());
145 //! # drop(file);
146 //! ~~~
147 //!
148 //! Or propagate the error up the call stack with `try!`:
149 //!
150 //! ~~~
151 //! # use std::io::{File, Open, Write, IoError};
152 //! fn write_message() -> Result<(), IoError> {
153 //!     let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
154 //!     try!(file.write_line("important message"));
155 //!     drop(file);
156 //!     return Ok(());
157 //! }
158 //! ~~~
159 //!
160 //! # The `try!` macro
161 //!
162 //! When writing code that calls many functions that return the
163 //! `Result` type, the error handling can be tedious.  The `try!`
164 //! macro hides some of the boilerplate of propagating errors up the
165 //! call stack.
166 //!
167 //! It replaces this:
168 //!
169 //! ~~~
170 //! use std::io::{File, Open, Write, IoError};
171 //!
172 //! struct Info { name: ~str, age: int, rating: int }
173 //!
174 //! fn write_info(info: &Info) -> Result<(), IoError> {
175 //!     let mut file = File::open_mode(&Path::new("my_best_friends.txt"), Open, Write);
176 //!     // Early return on error
177 //!     match file.write_line(format!("name: {}", info.name)) {
178 //!         Ok(_) => (),
179 //!         Err(e) => return Err(e)
180 //!     }
181 //!     match file.write_line(format!("age: {}", info.age)) {
182 //!         Ok(_) => (),
183 //!         Err(e) => return Err(e)
184 //!     }
185 //!     return file.write_line(format!("rating: {}", info.rating));
186 //! }
187 //! ~~~
188 //!
189 //! With this:
190 //!
191 //! ~~~
192 //! use std::io::{File, Open, Write, IoError};
193 //!
194 //! struct Info { name: ~str, age: int, rating: int }
195 //!
196 //! fn write_info(info: &Info) -> Result<(), IoError> {
197 //!     let mut file = File::open_mode(&Path::new("my_best_friends.txt"), Open, Write);
198 //!     // Early return on error
199 //!     try!(file.write_line(format!("name: {}", info.name)));
200 //!     try!(file.write_line(format!("age: {}", info.age)));
201 //!     try!(file.write_line(format!("rating: {}", info.rating)));
202 //!     return Ok(());
203 //! }
204 //! ~~~
205 //!
206 //! *It's much nicer!*
207 //!
208 //! Wrapping an expression in `try!` will result in the unwrapped
209 //! success (`Ok`) value, unless the result is `Err`, in which case
210 //! `Err` is returned early from the enclosing function. Its simple definition
211 //! makes it clear:
212 //!
213 //! ~~~
214 //! # #![feature(macro_rules)]
215 //! macro_rules! try(
216 //!     ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) })
217 //! )
218 //! # fn main() { }
219 //! ~~~
220 //!
221 //! `try!` is imported by the prelude, and is available everywhere.
222 //!
223 //! # `Result` and `Option`
224 //!
225 //! The `Result` and [`Option`](../option/index.html) types are
226 //! similar and complementary: they are often employed to indicate a
227 //! lack of a return value; and they are trivially converted between
228 //! each other, so `Result`s are often handled by first converting to
229 //! `Option` with the [`ok`](enum.Result.html#method.ok) and
230 //! [`err`](enum.Result.html#method.ok) methods.
231 //!
232 //! Whereas `Option` only indicates the lack of a value, `Result` is
233 //! specifically for error reporting, and carries with it an error
234 //! value.  Sometimes `Option` is used for indicating errors, but this
235 //! is only for simple cases and is generally discouraged. Even when
236 //! there is no useful error value to return, prefer `Result<T, ()>`.
237 //!
238 //! Converting to an `Option` with `ok()` to handle an error:
239 //!
240 //! ~~~
241 //! use std::io::Timer;
242 //! let mut t = Timer::new().ok().expect("failed to create timer!");
243 //! ~~~
244 //!
245 //! # `Result` vs. `fail!`
246 //!
247 //! `Result` is for recoverable errors; `fail!` is for unrecoverable
248 //! errors. Callers should always be able to avoid failure if they
249 //! take the proper precautions, for example, calling `is_some()`
250 //! on an `Option` type before calling `unwrap`.
251 //!
252 //! The suitability of `fail!` as an error handling mechanism is
253 //! limited by Rust's lack of any way to "catch" and resume execution
254 //! from a thrown exception. Therefore using failure for error
255 //! handling requires encapsulating fallable code in a task. Calling
256 //! the `fail!` macro, or invoking `fail!` indirectly should be
257 //! avoided as an error reporting strategy. Failure is only for
258 //! unrecoverable errors and a failing task is typically the sign of
259 //! a bug.
260 //!
261 //! A module that instead returns `Results` is alerting the caller
262 //! that failure is possible, and providing precise control over how
263 //! it is handled.
264 //!
265 //! Furthermore, failure may not be recoverable at all, depending on
266 //! the context. The caller of `fail!` should assume that execution
267 //! will not resume after failure, that failure is catastrophic.
268
269 use fmt::Show;
270
271 pub use core::result::{Result, Ok, Err, collect, fold, fold_};
272
273 // FIXME: These traits should not exist. Once std::fmt is moved to libcore,
274 //        these can once again become inherent methods on Result.
275
276 /// Temporary trait for unwrapping a result
277 pub trait ResultUnwrap<T, E> {
278     /// Unwraps a result, yielding the content of an `Ok`.
279     ///
280     /// Fails if the value is an `Err`.
281     fn unwrap(self) -> T;
282 }
283
284 /// Temporary trait for unwrapping the error of a result
285 pub trait ResultUnwrapErr<T, E> {
286     /// Unwraps a result, yielding the content of an `Err`.
287     ///
288     /// Fails if the value is an `Ok`.
289     fn unwrap_err(self) -> E;
290 }
291
292 impl<T, E: Show> ResultUnwrap<T, E> for Result<T, E> {
293     #[inline]
294     fn unwrap(self) -> T {
295         match self {
296             Ok(t) => t,
297             Err(e) =>
298                 fail!("called `Result::unwrap()` on an `Err` value: {}", e)
299         }
300     }
301 }
302
303 impl<T: Show, E> ResultUnwrapErr<T, E> for Result<T, E> {
304     #[inline]
305     fn unwrap_err(self) -> E {
306         match self {
307             Ok(t) =>
308                 fail!("called `Result::unwrap_err()` on an `Ok` value: {}", t),
309             Err(e) => e
310         }
311     }
312 }