Skip to content

Commit 9f3fd93

Browse files
committed
auto merge of #13499 : brson/rust/resultdocs, r=brson
This adds some fairly extensive documentation for `Result`. I'm using manual links to other rustdoc html pages a bit.
2 parents 88805e1 + e69bd81 commit 9f3fd93

File tree

1 file changed

+325
-5
lines changed

1 file changed

+325
-5
lines changed

src/libstd/result.rs

Lines changed: 325 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,263 @@
88
// option. This file may not be copied, modified, or distributed
99
// except according to those terms.
1010

11-
//! Signaling success or failure states (`Result` type)
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 synonymn 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+
//! unrecovereable 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.
12268
13269
use clone::Clone;
14270
use cmp::Eq;
@@ -17,6 +273,8 @@ use iter::{Iterator, FromIterator};
17273
use option::{None, Option, Some};
18274

19275
/// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
276+
///
277+
/// See the [`std::result`](index.html) module documentation for details.
20278
#[deriving(Clone, Eq, Ord, TotalEq, TotalOrd, Show)]
21279
#[must_use]
22280
pub enum Result<T, E> {
@@ -37,6 +295,17 @@ impl<T, E> Result<T, E> {
37295
/////////////////////////////////////////////////////////////////////////
38296

39297
/// Returns true if the result is `Ok`
298+
///
299+
/// # Example
300+
///
301+
/// ~~~
302+
/// use std::io::{File, Open, Write};
303+
///
304+
/// # fn do_not_run_example() { // creates a file
305+
/// let mut file = File::open_mode(&Path::new("secret.txt"), Open, Write);
306+
/// assert!(file.write_line("it's cold in here").is_ok());
307+
/// # }
308+
/// ~~~
40309
#[inline]
41310
pub fn is_ok(&self) -> bool {
42311
match *self {
@@ -46,6 +315,17 @@ impl<T, E> Result<T, E> {
46315
}
47316

48317
/// Returns true if the result is `Err`
318+
///
319+
/// # Example
320+
///
321+
/// ~~~
322+
/// use std::io::{File, Open, Read};
323+
///
324+
/// // When opening with `Read` access, if the file does not exist
325+
/// // then `open_mode` returns an error.
326+
/// let bogus = File::open_mode(&Path::new("not_a_file.txt"), Open, Read);
327+
/// assert!(bogus.is_err());
328+
/// ~~~
49329
#[inline]
50330
pub fn is_err(&self) -> bool {
51331
!self.is_ok()
@@ -57,6 +337,22 @@ impl<T, E> Result<T, E> {
57337
/////////////////////////////////////////////////////////////////////////
58338

59339
/// Convert from `Result<T, E>` to `Option<T>`
340+
///
341+
/// Converts `self` into an `Option<T>`, consuming `self`,
342+
/// and discarding the error, if any.
343+
///
344+
/// To convert to an `Option` without discarding the error value,
345+
/// use `as_ref` to first convert the `Result<T, E>` into a
346+
/// `Result<&T, &E>`.
347+
///
348+
/// # Examples
349+
///
350+
/// ~~~{.should_fail}
351+
/// use std::io::{File, IoResult};
352+
///
353+
/// let bdays: IoResult<File> = File::open(&Path::new("important_birthdays.txt"));
354+
/// let bdays: File = bdays.ok().expect("unable to open birthday file");
355+
/// ~~~
60356
#[inline]
61357
pub fn ok(self) -> Option<T> {
62358
match self {
@@ -66,6 +362,9 @@ impl<T, E> Result<T, E> {
66362
}
67363

68364
/// Convert from `Result<T, E>` to `Option<E>`
365+
///
366+
/// Converts `self` into an `Option<T>`, consuming `self`,
367+
/// and discarding the value, if any.
69368
#[inline]
70369
pub fn err(self) -> Option<E> {
71370
match self {
@@ -79,6 +378,9 @@ impl<T, E> Result<T, E> {
79378
/////////////////////////////////////////////////////////////////////////
80379

81380
/// Convert from `Result<T, E>` to `Result<&T, &E>`
381+
///
382+
/// Produces a new `Result`, containing a reference
383+
/// into the original, leaving the original in place.
82384
#[inline]
83385
pub fn as_ref<'r>(&'r self) -> Result<&'r T, &'r E> {
84386
match *self {
@@ -105,11 +407,29 @@ impl<T, E> Result<T, E> {
105407
///
106408
/// This function can be used to compose the results of two functions.
107409
///
108-
/// Example:
410+
/// # Examples
411+
///
412+
/// Sum the lines of a buffer by mapping strings to numbers,
413+
/// ignoring I/O and parse errors:
414+
///
415+
/// ~~~
416+
/// use std::io::{BufReader, IoResult};
417+
///
418+
/// let buffer = "1\n2\n3\n4\n";
419+
/// let mut reader = BufReader::new(buffer.as_bytes());
420+
///
421+
/// let mut sum = 0;
109422
///
110-
/// let res = read_file(file).map(|buf| {
111-
/// parse_bytes(buf)
112-
/// })
423+
/// while !reader.eof() {
424+
/// let line: IoResult<~str> = reader.read_line();
425+
/// // Convert the string line to a number using `map` and `from_str`
426+
/// let val: IoResult<int> = line.map(|line| {
427+
/// from_str::<int>(line).unwrap_or(0)
428+
/// });
429+
/// // Add the value if there were no errors, otherwise add 0
430+
/// sum += val.ok().unwrap_or(0);
431+
/// }
432+
/// ~~~
113433
#[inline]
114434
pub fn map<U>(self, op: |T| -> U) -> Result<U,E> {
115435
match self {

0 commit comments

Comments
 (0)