]> git.lizzy.rs Git - rust.git/blob - src/libcore/result.rs
Auto merge of #61754 - nikomatsakis:trait-caching-perf-3, r=pnkfelix
[rust.git] / src / libcore / result.rs
1 //! Error handling with the `Result` type.
2 //!
3 //! [`Result<T, E>`][`Result`] is the type used for returning and propagating
4 //! errors. It is an enum with the variants, [`Ok(T)`], representing
5 //! success and containing a value, and [`Err(E)`], representing error
6 //! and containing an error value.
7 //!
8 //! ```
9 //! # #[allow(dead_code)]
10 //! enum Result<T, E> {
11 //!    Ok(T),
12 //!    Err(E),
13 //! }
14 //! ```
15 //!
16 //! Functions return [`Result`] whenever errors are expected and
17 //! recoverable. In the `std` crate, [`Result`] is most prominently used
18 //! for [I/O](../../std/io/index.html).
19 //!
20 //! A simple function returning [`Result`] might be
21 //! defined and used like so:
22 //!
23 //! ```
24 //! #[derive(Debug)]
25 //! enum Version { Version1, Version2 }
26 //!
27 //! fn parse_version(header: &[u8]) -> Result<Version, &'static str> {
28 //!     match header.get(0) {
29 //!         None => Err("invalid header length"),
30 //!         Some(&1) => Ok(Version::Version1),
31 //!         Some(&2) => Ok(Version::Version2),
32 //!         Some(_) => Err("invalid version"),
33 //!     }
34 //! }
35 //!
36 //! let version = parse_version(&[1, 2, 3, 4]);
37 //! match version {
38 //!     Ok(v) => println!("working with version: {:?}", v),
39 //!     Err(e) => println!("error parsing header: {:?}", e),
40 //! }
41 //! ```
42 //!
43 //! Pattern matching on [`Result`]s is clear and straightforward for
44 //! simple cases, but [`Result`] comes with some convenience methods
45 //! that make working with it more succinct.
46 //!
47 //! ```
48 //! let good_result: Result<i32, i32> = Ok(10);
49 //! let bad_result: Result<i32, i32> = Err(10);
50 //!
51 //! // The `is_ok` and `is_err` methods do what they say.
52 //! assert!(good_result.is_ok() && !good_result.is_err());
53 //! assert!(bad_result.is_err() && !bad_result.is_ok());
54 //!
55 //! // `map` consumes the `Result` and produces another.
56 //! let good_result: Result<i32, i32> = good_result.map(|i| i + 1);
57 //! let bad_result: Result<i32, i32> = bad_result.map(|i| i - 1);
58 //!
59 //! // Use `and_then` to continue the computation.
60 //! let good_result: Result<bool, i32> = good_result.and_then(|i| Ok(i == 11));
61 //!
62 //! // Use `or_else` to handle the error.
63 //! let bad_result: Result<i32, i32> = bad_result.or_else(|i| Ok(i + 20));
64 //!
65 //! // Consume the result and return the contents with `unwrap`.
66 //! let final_awesome_result = good_result.unwrap();
67 //! ```
68 //!
69 //! # Results must be used
70 //!
71 //! A common problem with using return values to indicate errors is
72 //! that it is easy to ignore the return value, thus failing to handle
73 //! the error. [`Result`] is annotated with the `#[must_use]` attribute,
74 //! which will cause the compiler to issue a warning when a Result
75 //! value is ignored. This makes [`Result`] especially useful with
76 //! functions that may encounter errors but don't otherwise return a
77 //! useful value.
78 //!
79 //! Consider the [`write_all`] method defined for I/O types
80 //! by the [`Write`] trait:
81 //!
82 //! ```
83 //! use std::io;
84 //!
85 //! trait Write {
86 //!     fn write_all(&mut self, bytes: &[u8]) -> Result<(), io::Error>;
87 //! }
88 //! ```
89 //!
90 //! *Note: The actual definition of [`Write`] uses [`io::Result`], which
91 //! is just a synonym for [`Result`]`<T, `[`io::Error`]`>`.*
92 //!
93 //! This method doesn't produce a value, but the write may
94 //! fail. It's crucial to handle the error case, and *not* write
95 //! something like this:
96 //!
97 //! ```no_run
98 //! # #![allow(unused_must_use)] // \o/
99 //! use std::fs::File;
100 //! use std::io::prelude::*;
101 //!
102 //! let mut file = File::create("valuable_data.txt").unwrap();
103 //! // If `write_all` errors, then we'll never know, because the return
104 //! // value is ignored.
105 //! file.write_all(b"important message");
106 //! ```
107 //!
108 //! If you *do* write that in Rust, the compiler will give you a
109 //! warning (by default, controlled by the `unused_must_use` lint).
110 //!
111 //! You might instead, if you don't want to handle the error, simply
112 //! assert success with [`expect`]. This will panic if the
113 //! write fails, providing a marginally useful message indicating why:
114 //!
115 //! ```{.no_run}
116 //! use std::fs::File;
117 //! use std::io::prelude::*;
118 //!
119 //! let mut file = File::create("valuable_data.txt").unwrap();
120 //! file.write_all(b"important message").expect("failed to write message");
121 //! ```
122 //!
123 //! You might also simply assert success:
124 //!
125 //! ```{.no_run}
126 //! # use std::fs::File;
127 //! # use std::io::prelude::*;
128 //! # let mut file = File::create("valuable_data.txt").unwrap();
129 //! assert!(file.write_all(b"important message").is_ok());
130 //! ```
131 //!
132 //! Or propagate the error up the call stack with [`?`]:
133 //!
134 //! ```
135 //! # use std::fs::File;
136 //! # use std::io::prelude::*;
137 //! # use std::io;
138 //! # #[allow(dead_code)]
139 //! fn write_message() -> io::Result<()> {
140 //!     let mut file = File::create("valuable_data.txt")?;
141 //!     file.write_all(b"important message")?;
142 //!     Ok(())
143 //! }
144 //! ```
145 //!
146 //! # The question mark operator, `?`
147 //!
148 //! When writing code that calls many functions that return the
149 //! [`Result`] type, the error handling can be tedious. The question mark
150 //! operator, [`?`], hides some of the boilerplate of propagating errors
151 //! up the call stack.
152 //!
153 //! It replaces this:
154 //!
155 //! ```
156 //! # #![allow(dead_code)]
157 //! use std::fs::File;
158 //! use std::io::prelude::*;
159 //! use std::io;
160 //!
161 //! struct Info {
162 //!     name: String,
163 //!     age: i32,
164 //!     rating: i32,
165 //! }
166 //!
167 //! fn write_info(info: &Info) -> io::Result<()> {
168 //!     // Early return on error
169 //!     let mut file = match File::create("my_best_friends.txt") {
170 //!            Err(e) => return Err(e),
171 //!            Ok(f) => f,
172 //!     };
173 //!     if let Err(e) = file.write_all(format!("name: {}\n", info.name).as_bytes()) {
174 //!         return Err(e)
175 //!     }
176 //!     if let Err(e) = file.write_all(format!("age: {}\n", info.age).as_bytes()) {
177 //!         return Err(e)
178 //!     }
179 //!     if let Err(e) = file.write_all(format!("rating: {}\n", info.rating).as_bytes()) {
180 //!         return Err(e)
181 //!     }
182 //!     Ok(())
183 //! }
184 //! ```
185 //!
186 //! With this:
187 //!
188 //! ```
189 //! # #![allow(dead_code)]
190 //! use std::fs::File;
191 //! use std::io::prelude::*;
192 //! use std::io;
193 //!
194 //! struct Info {
195 //!     name: String,
196 //!     age: i32,
197 //!     rating: i32,
198 //! }
199 //!
200 //! fn write_info(info: &Info) -> io::Result<()> {
201 //!     let mut file = File::create("my_best_friends.txt")?;
202 //!     // Early return on error
203 //!     file.write_all(format!("name: {}\n", info.name).as_bytes())?;
204 //!     file.write_all(format!("age: {}\n", info.age).as_bytes())?;
205 //!     file.write_all(format!("rating: {}\n", info.rating).as_bytes())?;
206 //!     Ok(())
207 //! }
208 //! ```
209 //!
210 //! *It's much nicer!*
211 //!
212 //! Ending the expression with [`?`] will result in the unwrapped
213 //! success ([`Ok`]) value, unless the result is [`Err`], in which case
214 //! [`Err`] is returned early from the enclosing function.
215 //!
216 //! [`?`] can only be used in functions that return [`Result`] because of the
217 //! early return of [`Err`] that it provides.
218 //!
219 //! [`expect`]: enum.Result.html#method.expect
220 //! [`Write`]: ../../std/io/trait.Write.html
221 //! [`write_all`]: ../../std/io/trait.Write.html#method.write_all
222 //! [`io::Result`]: ../../std/io/type.Result.html
223 //! [`?`]: ../../std/macro.try.html
224 //! [`Result`]: enum.Result.html
225 //! [`Ok(T)`]: enum.Result.html#variant.Ok
226 //! [`Err(E)`]: enum.Result.html#variant.Err
227 //! [`io::Error`]: ../../std/io/struct.Error.html
228 //! [`Ok`]: enum.Result.html#variant.Ok
229 //! [`Err`]: enum.Result.html#variant.Err
230
231 #![stable(feature = "rust1", since = "1.0.0")]
232
233 use crate::fmt;
234 use crate::iter::{FromIterator, FusedIterator, TrustedLen};
235 use crate::ops::{self, Deref};
236
237 /// `Result` is a type that represents either success ([`Ok`]) or failure ([`Err`]).
238 ///
239 /// See the [`std::result`](index.html) module documentation for details.
240 ///
241 /// [`Ok`]: enum.Result.html#variant.Ok
242 /// [`Err`]: enum.Result.html#variant.Err
243 #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
244 #[must_use = "this `Result` may be an `Err` variant, which should be handled"]
245 #[stable(feature = "rust1", since = "1.0.0")]
246 pub enum Result<T, E> {
247     /// Contains the success value
248     #[stable(feature = "rust1", since = "1.0.0")]
249     Ok(#[stable(feature = "rust1", since = "1.0.0")] T),
250
251     /// Contains the error value
252     #[stable(feature = "rust1", since = "1.0.0")]
253     Err(#[stable(feature = "rust1", since = "1.0.0")] E),
254 }
255
256 /////////////////////////////////////////////////////////////////////////////
257 // Type implementation
258 /////////////////////////////////////////////////////////////////////////////
259
260 impl<T, E> Result<T, E> {
261     /////////////////////////////////////////////////////////////////////////
262     // Querying the contained values
263     /////////////////////////////////////////////////////////////////////////
264
265     /// Returns `true` if the result is [`Ok`].
266     ///
267     /// [`Ok`]: enum.Result.html#variant.Ok
268     ///
269     /// # Examples
270     ///
271     /// Basic usage:
272     ///
273     /// ```
274     /// let x: Result<i32, &str> = Ok(-3);
275     /// assert_eq!(x.is_ok(), true);
276     ///
277     /// let x: Result<i32, &str> = Err("Some error message");
278     /// assert_eq!(x.is_ok(), false);
279     /// ```
280     #[must_use]
281     #[inline]
282     #[stable(feature = "rust1", since = "1.0.0")]
283     pub fn is_ok(&self) -> bool {
284         match *self {
285             Ok(_) => true,
286             Err(_) => false
287         }
288     }
289
290     /// Returns `true` if the result is [`Err`].
291     ///
292     /// [`Err`]: enum.Result.html#variant.Err
293     ///
294     /// # Examples
295     ///
296     /// Basic usage:
297     ///
298     /// ```
299     /// let x: Result<i32, &str> = Ok(-3);
300     /// assert_eq!(x.is_err(), false);
301     ///
302     /// let x: Result<i32, &str> = Err("Some error message");
303     /// assert_eq!(x.is_err(), true);
304     /// ```
305     #[must_use]
306     #[inline]
307     #[stable(feature = "rust1", since = "1.0.0")]
308     pub fn is_err(&self) -> bool {
309         !self.is_ok()
310     }
311
312     /////////////////////////////////////////////////////////////////////////
313     // Adapter for each variant
314     /////////////////////////////////////////////////////////////////////////
315
316     /// Converts from `Result<T, E>` to [`Option<T>`].
317     ///
318     /// Converts `self` into an [`Option<T>`], consuming `self`,
319     /// and discarding the error, if any.
320     ///
321     /// [`Option<T>`]: ../../std/option/enum.Option.html
322     ///
323     /// # Examples
324     ///
325     /// Basic usage:
326     ///
327     /// ```
328     /// let x: Result<u32, &str> = Ok(2);
329     /// assert_eq!(x.ok(), Some(2));
330     ///
331     /// let x: Result<u32, &str> = Err("Nothing here");
332     /// assert_eq!(x.ok(), None);
333     /// ```
334     #[inline]
335     #[stable(feature = "rust1", since = "1.0.0")]
336     pub fn ok(self) -> Option<T> {
337         match self {
338             Ok(x)  => Some(x),
339             Err(_) => None,
340         }
341     }
342
343     /// Converts from `Result<T, E>` to [`Option<E>`].
344     ///
345     /// Converts `self` into an [`Option<E>`], consuming `self`,
346     /// and discarding the success value, if any.
347     ///
348     /// [`Option<E>`]: ../../std/option/enum.Option.html
349     ///
350     /// # Examples
351     ///
352     /// Basic usage:
353     ///
354     /// ```
355     /// let x: Result<u32, &str> = Ok(2);
356     /// assert_eq!(x.err(), None);
357     ///
358     /// let x: Result<u32, &str> = Err("Nothing here");
359     /// assert_eq!(x.err(), Some("Nothing here"));
360     /// ```
361     #[inline]
362     #[stable(feature = "rust1", since = "1.0.0")]
363     pub fn err(self) -> Option<E> {
364         match self {
365             Ok(_)  => None,
366             Err(x) => Some(x),
367         }
368     }
369
370     /////////////////////////////////////////////////////////////////////////
371     // Adapter for working with references
372     /////////////////////////////////////////////////////////////////////////
373
374     /// Converts from `&Result<T, E>` to `Result<&T, &E>`.
375     ///
376     /// Produces a new `Result`, containing a reference
377     /// into the original, leaving the original in place.
378     ///
379     /// # Examples
380     ///
381     /// Basic usage:
382     ///
383     /// ```
384     /// let x: Result<u32, &str> = Ok(2);
385     /// assert_eq!(x.as_ref(), Ok(&2));
386     ///
387     /// let x: Result<u32, &str> = Err("Error");
388     /// assert_eq!(x.as_ref(), Err(&"Error"));
389     /// ```
390     #[inline]
391     #[stable(feature = "rust1", since = "1.0.0")]
392     pub fn as_ref(&self) -> Result<&T, &E> {
393         match *self {
394             Ok(ref x) => Ok(x),
395             Err(ref x) => Err(x),
396         }
397     }
398
399     /// Converts from `&mut Result<T, E>` to `Result<&mut T, &mut E>`.
400     ///
401     /// # Examples
402     ///
403     /// Basic usage:
404     ///
405     /// ```
406     /// fn mutate(r: &mut Result<i32, i32>) {
407     ///     match r.as_mut() {
408     ///         Ok(v) => *v = 42,
409     ///         Err(e) => *e = 0,
410     ///     }
411     /// }
412     ///
413     /// let mut x: Result<i32, i32> = Ok(2);
414     /// mutate(&mut x);
415     /// assert_eq!(x.unwrap(), 42);
416     ///
417     /// let mut x: Result<i32, i32> = Err(13);
418     /// mutate(&mut x);
419     /// assert_eq!(x.unwrap_err(), 0);
420     /// ```
421     #[inline]
422     #[stable(feature = "rust1", since = "1.0.0")]
423     pub fn as_mut(&mut self) -> Result<&mut T, &mut E> {
424         match *self {
425             Ok(ref mut x) => Ok(x),
426             Err(ref mut x) => Err(x),
427         }
428     }
429
430     /////////////////////////////////////////////////////////////////////////
431     // Transforming contained values
432     /////////////////////////////////////////////////////////////////////////
433
434     /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a
435     /// contained [`Ok`] value, leaving an [`Err`] value untouched.
436     ///
437     /// This function can be used to compose the results of two functions.
438     ///
439     /// [`Ok`]: enum.Result.html#variant.Ok
440     /// [`Err`]: enum.Result.html#variant.Err
441     ///
442     /// # Examples
443     ///
444     /// Print the numbers on each line of a string multiplied by two.
445     ///
446     /// ```
447     /// let line = "1\n2\n3\n4\n";
448     ///
449     /// for num in line.lines() {
450     ///     match num.parse::<i32>().map(|i| i * 2) {
451     ///         Ok(n) => println!("{}", n),
452     ///         Err(..) => {}
453     ///     }
454     /// }
455     /// ```
456     #[inline]
457     #[stable(feature = "rust1", since = "1.0.0")]
458     pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U,E> {
459         match self {
460             Ok(t) => Ok(op(t)),
461             Err(e) => Err(e)
462         }
463     }
464
465     /// Maps a `Result<T, E>` to `U` by applying a function to a
466     /// contained [`Ok`] value, or a fallback function to a
467     /// contained [`Err`] value.
468     ///
469     /// This function can be used to unpack a successful result
470     /// while handling an error.
471     ///
472     /// [`Ok`]: enum.Result.html#variant.Ok
473     /// [`Err`]: enum.Result.html#variant.Err
474     ///
475     /// # Examples
476     ///
477     /// Basic usage:
478     ///
479     /// ```
480     /// #![feature(result_map_or_else)]
481     /// let k = 21;
482     ///
483     /// let x : Result<_, &str> = Ok("foo");
484     /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 3);
485     ///
486     /// let x : Result<&str, _> = Err("bar");
487     /// assert_eq!(x.map_or_else(|e| k * 2, |v| v.len()), 42);
488     /// ```
489     #[inline]
490     #[unstable(feature = "result_map_or_else", issue = "53268")]
491     pub fn map_or_else<U, M: FnOnce(T) -> U, F: FnOnce(E) -> U>(self, fallback: F, map: M) -> U {
492         self.map(map).unwrap_or_else(fallback)
493     }
494
495     /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
496     /// contained [`Err`] value, leaving an [`Ok`] value untouched.
497     ///
498     /// This function can be used to pass through a successful result while handling
499     /// an error.
500     ///
501     /// [`Ok`]: enum.Result.html#variant.Ok
502     /// [`Err`]: enum.Result.html#variant.Err
503     ///
504     /// # Examples
505     ///
506     /// Basic usage:
507     ///
508     /// ```
509     /// fn stringify(x: u32) -> String { format!("error code: {}", x) }
510     ///
511     /// let x: Result<u32, u32> = Ok(2);
512     /// assert_eq!(x.map_err(stringify), Ok(2));
513     ///
514     /// let x: Result<u32, u32> = Err(13);
515     /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
516     /// ```
517     #[inline]
518     #[stable(feature = "rust1", since = "1.0.0")]
519     pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T,F> {
520         match self {
521             Ok(t) => Ok(t),
522             Err(e) => Err(op(e))
523         }
524     }
525
526     /////////////////////////////////////////////////////////////////////////
527     // Iterator constructors
528     /////////////////////////////////////////////////////////////////////////
529
530     /// Returns an iterator over the possibly contained value.
531     ///
532     /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
533     ///
534     /// # Examples
535     ///
536     /// Basic usage:
537     ///
538     /// ```
539     /// let x: Result<u32, &str> = Ok(7);
540     /// assert_eq!(x.iter().next(), Some(&7));
541     ///
542     /// let x: Result<u32, &str> = Err("nothing!");
543     /// assert_eq!(x.iter().next(), None);
544     /// ```
545     #[inline]
546     #[stable(feature = "rust1", since = "1.0.0")]
547     pub fn iter(&self) -> Iter<'_, T> {
548         Iter { inner: self.as_ref().ok() }
549     }
550
551     /// Returns a mutable iterator over the possibly contained value.
552     ///
553     /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
554     ///
555     /// # Examples
556     ///
557     /// Basic usage:
558     ///
559     /// ```
560     /// let mut x: Result<u32, &str> = Ok(7);
561     /// match x.iter_mut().next() {
562     ///     Some(v) => *v = 40,
563     ///     None => {},
564     /// }
565     /// assert_eq!(x, Ok(40));
566     ///
567     /// let mut x: Result<u32, &str> = Err("nothing!");
568     /// assert_eq!(x.iter_mut().next(), None);
569     /// ```
570     #[inline]
571     #[stable(feature = "rust1", since = "1.0.0")]
572     pub fn iter_mut(&mut self) -> IterMut<'_, T> {
573         IterMut { inner: self.as_mut().ok() }
574     }
575
576     ////////////////////////////////////////////////////////////////////////
577     // Boolean operations on the values, eager and lazy
578     /////////////////////////////////////////////////////////////////////////
579
580     /// Returns `res` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
581     ///
582     /// [`Ok`]: enum.Result.html#variant.Ok
583     /// [`Err`]: enum.Result.html#variant.Err
584     ///
585     /// # Examples
586     ///
587     /// Basic usage:
588     ///
589     /// ```
590     /// let x: Result<u32, &str> = Ok(2);
591     /// let y: Result<&str, &str> = Err("late error");
592     /// assert_eq!(x.and(y), Err("late error"));
593     ///
594     /// let x: Result<u32, &str> = Err("early error");
595     /// let y: Result<&str, &str> = Ok("foo");
596     /// assert_eq!(x.and(y), Err("early error"));
597     ///
598     /// let x: Result<u32, &str> = Err("not a 2");
599     /// let y: Result<&str, &str> = Err("late error");
600     /// assert_eq!(x.and(y), Err("not a 2"));
601     ///
602     /// let x: Result<u32, &str> = Ok(2);
603     /// let y: Result<&str, &str> = Ok("different result type");
604     /// assert_eq!(x.and(y), Ok("different result type"));
605     /// ```
606     #[inline]
607     #[stable(feature = "rust1", since = "1.0.0")]
608     pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
609         match self {
610             Ok(_) => res,
611             Err(e) => Err(e),
612         }
613     }
614
615     /// Calls `op` if the result is [`Ok`], otherwise returns the [`Err`] value of `self`.
616     ///
617     /// [`Ok`]: enum.Result.html#variant.Ok
618     /// [`Err`]: enum.Result.html#variant.Err
619     ///
620     /// This function can be used for control flow based on `Result` values.
621     ///
622     /// # Examples
623     ///
624     /// Basic usage:
625     ///
626     /// ```
627     /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
628     /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
629     ///
630     /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
631     /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
632     /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
633     /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
634     /// ```
635     #[inline]
636     #[stable(feature = "rust1", since = "1.0.0")]
637     pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
638         match self {
639             Ok(t) => op(t),
640             Err(e) => Err(e),
641         }
642     }
643
644     /// Returns `res` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
645     ///
646     /// Arguments passed to `or` are eagerly evaluated; if you are passing the
647     /// result of a function call, it is recommended to use [`or_else`], which is
648     /// lazily evaluated.
649     ///
650     /// [`Ok`]: enum.Result.html#variant.Ok
651     /// [`Err`]: enum.Result.html#variant.Err
652     /// [`or_else`]: #method.or_else
653     ///
654     /// # Examples
655     ///
656     /// Basic usage:
657     ///
658     /// ```
659     /// let x: Result<u32, &str> = Ok(2);
660     /// let y: Result<u32, &str> = Err("late error");
661     /// assert_eq!(x.or(y), Ok(2));
662     ///
663     /// let x: Result<u32, &str> = Err("early error");
664     /// let y: Result<u32, &str> = Ok(2);
665     /// assert_eq!(x.or(y), Ok(2));
666     ///
667     /// let x: Result<u32, &str> = Err("not a 2");
668     /// let y: Result<u32, &str> = Err("late error");
669     /// assert_eq!(x.or(y), Err("late error"));
670     ///
671     /// let x: Result<u32, &str> = Ok(2);
672     /// let y: Result<u32, &str> = Ok(100);
673     /// assert_eq!(x.or(y), Ok(2));
674     /// ```
675     #[inline]
676     #[stable(feature = "rust1", since = "1.0.0")]
677     pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
678         match self {
679             Ok(v) => Ok(v),
680             Err(_) => res,
681         }
682     }
683
684     /// Calls `op` if the result is [`Err`], otherwise returns the [`Ok`] value of `self`.
685     ///
686     /// This function can be used for control flow based on result values.
687     ///
688     /// [`Ok`]: enum.Result.html#variant.Ok
689     /// [`Err`]: enum.Result.html#variant.Err
690     ///
691     /// # Examples
692     ///
693     /// Basic usage:
694     ///
695     /// ```
696     /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
697     /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
698     ///
699     /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
700     /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
701     /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
702     /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
703     /// ```
704     #[inline]
705     #[stable(feature = "rust1", since = "1.0.0")]
706     pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
707         match self {
708             Ok(t) => Ok(t),
709             Err(e) => op(e),
710         }
711     }
712
713     /// Unwraps a result, yielding the content of an [`Ok`].
714     /// Else, it returns `optb`.
715     ///
716     /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing
717     /// the result of a function call, it is recommended to use [`unwrap_or_else`],
718     /// which is lazily evaluated.
719     ///
720     /// [`Ok`]: enum.Result.html#variant.Ok
721     /// [`Err`]: enum.Result.html#variant.Err
722     /// [`unwrap_or_else`]: #method.unwrap_or_else
723     ///
724     /// # Examples
725     ///
726     /// Basic usage:
727     ///
728     /// ```
729     /// let optb = 2;
730     /// let x: Result<u32, &str> = Ok(9);
731     /// assert_eq!(x.unwrap_or(optb), 9);
732     ///
733     /// let x: Result<u32, &str> = Err("error");
734     /// assert_eq!(x.unwrap_or(optb), optb);
735     /// ```
736     #[inline]
737     #[stable(feature = "rust1", since = "1.0.0")]
738     pub fn unwrap_or(self, optb: T) -> T {
739         match self {
740             Ok(t) => t,
741             Err(_) => optb
742         }
743     }
744
745     /// Unwraps a result, yielding the content of an [`Ok`].
746     /// If the value is an [`Err`] then it calls `op` with its value.
747     ///
748     /// [`Ok`]: enum.Result.html#variant.Ok
749     /// [`Err`]: enum.Result.html#variant.Err
750     ///
751     /// # Examples
752     ///
753     /// Basic usage:
754     ///
755     /// ```
756     /// fn count(x: &str) -> usize { x.len() }
757     ///
758     /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
759     /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
760     /// ```
761     #[inline]
762     #[stable(feature = "rust1", since = "1.0.0")]
763     pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
764         match self {
765             Ok(t) => t,
766             Err(e) => op(e)
767         }
768     }
769 }
770
771 impl<T, E: fmt::Debug> Result<T, E> {
772     /// Unwraps a result, yielding the content of an [`Ok`].
773     ///
774     /// # Panics
775     ///
776     /// Panics if the value is an [`Err`], with a panic message provided by the
777     /// [`Err`]'s value.
778     ///
779     /// [`Ok`]: enum.Result.html#variant.Ok
780     /// [`Err`]: enum.Result.html#variant.Err
781     ///
782     /// # Examples
783     ///
784     /// Basic usage:
785     ///
786     /// ```
787     /// let x: Result<u32, &str> = Ok(2);
788     /// assert_eq!(x.unwrap(), 2);
789     /// ```
790     ///
791     /// ```{.should_panic}
792     /// let x: Result<u32, &str> = Err("emergency failure");
793     /// x.unwrap(); // panics with `emergency failure`
794     /// ```
795     #[inline]
796     #[stable(feature = "rust1", since = "1.0.0")]
797     pub fn unwrap(self) -> T {
798         match self {
799             Ok(t) => t,
800             Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", e),
801         }
802     }
803
804     /// Unwraps a result, yielding the content of an [`Ok`].
805     ///
806     /// # Panics
807     ///
808     /// Panics if the value is an [`Err`], with a panic message including the
809     /// passed message, and the content of the [`Err`].
810     ///
811     /// [`Ok`]: enum.Result.html#variant.Ok
812     /// [`Err`]: enum.Result.html#variant.Err
813     ///
814     /// # Examples
815     ///
816     /// Basic usage:
817     ///
818     /// ```{.should_panic}
819     /// let x: Result<u32, &str> = Err("emergency failure");
820     /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
821     /// ```
822     #[inline]
823     #[stable(feature = "result_expect", since = "1.4.0")]
824     pub fn expect(self, msg: &str) -> T {
825         match self {
826             Ok(t) => t,
827             Err(e) => unwrap_failed(msg, e),
828         }
829     }
830 }
831
832 impl<T: fmt::Debug, E> Result<T, E> {
833     /// Unwraps a result, yielding the content of an [`Err`].
834     ///
835     /// # Panics
836     ///
837     /// Panics if the value is an [`Ok`], with a custom panic message provided
838     /// by the [`Ok`]'s value.
839     ///
840     /// [`Ok`]: enum.Result.html#variant.Ok
841     /// [`Err`]: enum.Result.html#variant.Err
842     ///
843     ///
844     /// # Examples
845     ///
846     /// ```{.should_panic}
847     /// let x: Result<u32, &str> = Ok(2);
848     /// x.unwrap_err(); // panics with `2`
849     /// ```
850     ///
851     /// ```
852     /// let x: Result<u32, &str> = Err("emergency failure");
853     /// assert_eq!(x.unwrap_err(), "emergency failure");
854     /// ```
855     #[inline]
856     #[stable(feature = "rust1", since = "1.0.0")]
857     pub fn unwrap_err(self) -> E {
858         match self {
859             Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", t),
860             Err(e) => e,
861         }
862     }
863
864     /// Unwraps a result, yielding the content of an [`Err`].
865     ///
866     /// # Panics
867     ///
868     /// Panics if the value is an [`Ok`], with a panic message including the
869     /// passed message, and the content of the [`Ok`].
870     ///
871     /// [`Ok`]: enum.Result.html#variant.Ok
872     /// [`Err`]: enum.Result.html#variant.Err
873     ///
874     /// # Examples
875     ///
876     /// Basic usage:
877     ///
878     /// ```{.should_panic}
879     /// let x: Result<u32, &str> = Ok(10);
880     /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
881     /// ```
882     #[inline]
883     #[stable(feature = "result_expect_err", since = "1.17.0")]
884     pub fn expect_err(self, msg: &str) -> E {
885         match self {
886             Ok(t) => unwrap_failed(msg, t),
887             Err(e) => e,
888         }
889     }
890 }
891
892 impl<T: Default, E> Result<T, E> {
893     /// Returns the contained value or a default
894     ///
895     /// Consumes the `self` argument then, if [`Ok`], returns the contained
896     /// value, otherwise if [`Err`], returns the default value for that
897     /// type.
898     ///
899     /// # Examples
900     ///
901     /// Converts a string to an integer, turning poorly-formed strings
902     /// into 0 (the default value for integers). [`parse`] converts
903     /// a string to any other type that implements [`FromStr`], returning an
904     /// [`Err`] on error.
905     ///
906     /// ```
907     /// let good_year_from_input = "1909";
908     /// let bad_year_from_input = "190blarg";
909     /// let good_year = good_year_from_input.parse().unwrap_or_default();
910     /// let bad_year = bad_year_from_input.parse().unwrap_or_default();
911     ///
912     /// assert_eq!(1909, good_year);
913     /// assert_eq!(0, bad_year);
914     /// ```
915     ///
916     /// [`parse`]: ../../std/primitive.str.html#method.parse
917     /// [`FromStr`]: ../../std/str/trait.FromStr.html
918     /// [`Ok`]: enum.Result.html#variant.Ok
919     /// [`Err`]: enum.Result.html#variant.Err
920     #[inline]
921     #[stable(feature = "result_unwrap_or_default", since = "1.16.0")]
922     pub fn unwrap_or_default(self) -> T {
923         match self {
924             Ok(x) => x,
925             Err(_) => Default::default(),
926         }
927     }
928 }
929
930 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
931 impl<T: Deref, E> Result<T, E> {
932     /// Converts from `&Result<T, E>` to `Result<&T::Target, &E>`.
933     ///
934     /// Leaves the original Result in-place, creating a new one with a reference
935     /// to the original one, additionally coercing the `Ok` arm of the Result via
936     /// `Deref`.
937     pub fn deref_ok(&self) -> Result<&T::Target, &E> {
938         self.as_ref().map(|t| t.deref())
939     }
940 }
941
942 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
943 impl<T, E: Deref> Result<T, E> {
944     /// Converts from `&Result<T, E>` to `Result<&T, &E::Target>`.
945     ///
946     /// Leaves the original Result in-place, creating a new one with a reference
947     /// to the original one, additionally coercing the `Err` arm of the Result via
948     /// `Deref`.
949     pub fn deref_err(&self) -> Result<&T, &E::Target>
950     {
951         self.as_ref().map_err(|e| e.deref())
952     }
953 }
954
955 #[unstable(feature = "inner_deref", reason = "newly added", issue = "50264")]
956 impl<T: Deref, E: Deref> Result<T, E> {
957     /// Converts from `&Result<T, E>` to `Result<&T::Target, &E::Target>`.
958     ///
959     /// Leaves the original Result in-place, creating a new one with a reference
960     /// to the original one, additionally coercing both the `Ok` and `Err` arms
961     /// of the Result via `Deref`.
962     pub fn deref(&self) -> Result<&T::Target, &E::Target>
963     {
964         self.as_ref().map(|t| t.deref()).map_err(|e| e.deref())
965     }
966 }
967
968 impl<T, E> Result<Option<T>, E> {
969     /// Transposes a `Result` of an `Option` into an `Option` of a `Result`.
970     ///
971     /// `Ok(None)` will be mapped to `None`.
972     /// `Ok(Some(_))` and `Err(_)` will be mapped to `Some(Ok(_))` and `Some(Err(_))`.
973     ///
974     /// # Examples
975     ///
976     /// ```
977     /// #[derive(Debug, Eq, PartialEq)]
978     /// struct SomeErr;
979     ///
980     /// let x: Result<Option<i32>, SomeErr> = Ok(Some(5));
981     /// let y: Option<Result<i32, SomeErr>> = Some(Ok(5));
982     /// assert_eq!(x.transpose(), y);
983     /// ```
984     #[inline]
985     #[stable(feature = "transpose_result", since = "1.33.0")]
986     pub fn transpose(self) -> Option<Result<T, E>> {
987         match self {
988             Ok(Some(x)) => Some(Ok(x)),
989             Ok(None) => None,
990             Err(e) => Some(Err(e)),
991         }
992     }
993 }
994
995 // This is a separate function to reduce the code size of the methods
996 #[inline(never)]
997 #[cold]
998 fn unwrap_failed<E: fmt::Debug>(msg: &str, error: E) -> ! {
999     panic!("{}: {:?}", msg, error)
1000 }
1001
1002 /////////////////////////////////////////////////////////////////////////////
1003 // Trait implementations
1004 /////////////////////////////////////////////////////////////////////////////
1005
1006 #[stable(feature = "rust1", since = "1.0.0")]
1007 impl<T: Clone, E: Clone> Clone for Result<T, E> {
1008     #[inline]
1009     fn clone(&self) -> Self {
1010         match self {
1011             Ok(x) => Ok(x.clone()),
1012             Err(x) => Err(x.clone()),
1013         }
1014     }
1015
1016     #[inline]
1017     fn clone_from(&mut self, source: &Self) {
1018         match (self, source) {
1019             (Ok(to), Ok(from)) => to.clone_from(from),
1020             (Err(to), Err(from)) => to.clone_from(from),
1021             (to, from) => *to = from.clone(),
1022         }
1023     }
1024 }
1025
1026
1027 #[stable(feature = "rust1", since = "1.0.0")]
1028 impl<T, E> IntoIterator for Result<T, E> {
1029     type Item = T;
1030     type IntoIter = IntoIter<T>;
1031
1032     /// Returns a consuming iterator over the possibly contained value.
1033     ///
1034     /// The iterator yields one value if the result is [`Result::Ok`], otherwise none.
1035     ///
1036     /// # Examples
1037     ///
1038     /// Basic usage:
1039     ///
1040     /// ```
1041     /// let x: Result<u32, &str> = Ok(5);
1042     /// let v: Vec<u32> = x.into_iter().collect();
1043     /// assert_eq!(v, [5]);
1044     ///
1045     /// let x: Result<u32, &str> = Err("nothing!");
1046     /// let v: Vec<u32> = x.into_iter().collect();
1047     /// assert_eq!(v, []);
1048     /// ```
1049     #[inline]
1050     fn into_iter(self) -> IntoIter<T> {
1051         IntoIter { inner: self.ok() }
1052     }
1053 }
1054
1055 #[stable(since = "1.4.0", feature = "result_iter")]
1056 impl<'a, T, E> IntoIterator for &'a Result<T, E> {
1057     type Item = &'a T;
1058     type IntoIter = Iter<'a, T>;
1059
1060     fn into_iter(self) -> Iter<'a, T> {
1061         self.iter()
1062     }
1063 }
1064
1065 #[stable(since = "1.4.0", feature = "result_iter")]
1066 impl<'a, T, E> IntoIterator for &'a mut Result<T, E> {
1067     type Item = &'a mut T;
1068     type IntoIter = IterMut<'a, T>;
1069
1070     fn into_iter(self) -> IterMut<'a, T> {
1071         self.iter_mut()
1072     }
1073 }
1074
1075 /////////////////////////////////////////////////////////////////////////////
1076 // The Result Iterators
1077 /////////////////////////////////////////////////////////////////////////////
1078
1079 /// An iterator over a reference to the [`Ok`] variant of a [`Result`].
1080 ///
1081 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1082 ///
1083 /// Created by [`Result::iter`].
1084 ///
1085 /// [`Ok`]: enum.Result.html#variant.Ok
1086 /// [`Result`]: enum.Result.html
1087 /// [`Result::iter`]: enum.Result.html#method.iter
1088 #[derive(Debug)]
1089 #[stable(feature = "rust1", since = "1.0.0")]
1090 pub struct Iter<'a, T: 'a> { inner: Option<&'a T> }
1091
1092 #[stable(feature = "rust1", since = "1.0.0")]
1093 impl<'a, T> Iterator for Iter<'a, T> {
1094     type Item = &'a T;
1095
1096     #[inline]
1097     fn next(&mut self) -> Option<&'a T> { self.inner.take() }
1098     #[inline]
1099     fn size_hint(&self) -> (usize, Option<usize>) {
1100         let n = if self.inner.is_some() {1} else {0};
1101         (n, Some(n))
1102     }
1103 }
1104
1105 #[stable(feature = "rust1", since = "1.0.0")]
1106 impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
1107     #[inline]
1108     fn next_back(&mut self) -> Option<&'a T> { self.inner.take() }
1109 }
1110
1111 #[stable(feature = "rust1", since = "1.0.0")]
1112 impl<T> ExactSizeIterator for Iter<'_, T> {}
1113
1114 #[stable(feature = "fused", since = "1.26.0")]
1115 impl<T> FusedIterator for Iter<'_, T> {}
1116
1117 #[unstable(feature = "trusted_len", issue = "37572")]
1118 unsafe impl<A> TrustedLen for Iter<'_, A> {}
1119
1120 #[stable(feature = "rust1", since = "1.0.0")]
1121 impl<T> Clone for Iter<'_, T> {
1122     #[inline]
1123     fn clone(&self) -> Self { Iter { inner: self.inner } }
1124 }
1125
1126 /// An iterator over a mutable reference to the [`Ok`] variant of a [`Result`].
1127 ///
1128 /// Created by [`Result::iter_mut`].
1129 ///
1130 /// [`Ok`]: enum.Result.html#variant.Ok
1131 /// [`Result`]: enum.Result.html
1132 /// [`Result::iter_mut`]: enum.Result.html#method.iter_mut
1133 #[derive(Debug)]
1134 #[stable(feature = "rust1", since = "1.0.0")]
1135 pub struct IterMut<'a, T: 'a> { inner: Option<&'a mut T> }
1136
1137 #[stable(feature = "rust1", since = "1.0.0")]
1138 impl<'a, T> Iterator for IterMut<'a, T> {
1139     type Item = &'a mut T;
1140
1141     #[inline]
1142     fn next(&mut self) -> Option<&'a mut T> { self.inner.take() }
1143     #[inline]
1144     fn size_hint(&self) -> (usize, Option<usize>) {
1145         let n = if self.inner.is_some() {1} else {0};
1146         (n, Some(n))
1147     }
1148 }
1149
1150 #[stable(feature = "rust1", since = "1.0.0")]
1151 impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
1152     #[inline]
1153     fn next_back(&mut self) -> Option<&'a mut T> { self.inner.take() }
1154 }
1155
1156 #[stable(feature = "rust1", since = "1.0.0")]
1157 impl<T> ExactSizeIterator for IterMut<'_, T> {}
1158
1159 #[stable(feature = "fused", since = "1.26.0")]
1160 impl<T> FusedIterator for IterMut<'_, T> {}
1161
1162 #[unstable(feature = "trusted_len", issue = "37572")]
1163 unsafe impl<A> TrustedLen for IterMut<'_, A> {}
1164
1165 /// An iterator over the value in a [`Ok`] variant of a [`Result`].
1166 ///
1167 /// The iterator yields one value if the result is [`Ok`], otherwise none.
1168 ///
1169 /// This struct is created by the [`into_iter`] method on
1170 /// [`Result`][`Result`] (provided by the [`IntoIterator`] trait).
1171 ///
1172 /// [`Ok`]: enum.Result.html#variant.Ok
1173 /// [`Result`]: enum.Result.html
1174 /// [`into_iter`]: ../iter/trait.IntoIterator.html#tymethod.into_iter
1175 /// [`IntoIterator`]: ../iter/trait.IntoIterator.html
1176 #[derive(Clone, Debug)]
1177 #[stable(feature = "rust1", since = "1.0.0")]
1178 pub struct IntoIter<T> { inner: Option<T> }
1179
1180 #[stable(feature = "rust1", since = "1.0.0")]
1181 impl<T> Iterator for IntoIter<T> {
1182     type Item = T;
1183
1184     #[inline]
1185     fn next(&mut self) -> Option<T> { self.inner.take() }
1186     #[inline]
1187     fn size_hint(&self) -> (usize, Option<usize>) {
1188         let n = if self.inner.is_some() {1} else {0};
1189         (n, Some(n))
1190     }
1191 }
1192
1193 #[stable(feature = "rust1", since = "1.0.0")]
1194 impl<T> DoubleEndedIterator for IntoIter<T> {
1195     #[inline]
1196     fn next_back(&mut self) -> Option<T> { self.inner.take() }
1197 }
1198
1199 #[stable(feature = "rust1", since = "1.0.0")]
1200 impl<T> ExactSizeIterator for IntoIter<T> {}
1201
1202 #[stable(feature = "fused", since = "1.26.0")]
1203 impl<T> FusedIterator for IntoIter<T> {}
1204
1205 #[unstable(feature = "trusted_len", issue = "37572")]
1206 unsafe impl<A> TrustedLen for IntoIter<A> {}
1207
1208 /////////////////////////////////////////////////////////////////////////////
1209 // FromIterator
1210 /////////////////////////////////////////////////////////////////////////////
1211
1212 #[stable(feature = "rust1", since = "1.0.0")]
1213 impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
1214     /// Takes each element in the `Iterator`: if it is an `Err`, no further
1215     /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
1216     /// container with the values of each `Result` is returned.
1217     ///
1218     /// Here is an example which increments every integer in a vector,
1219     /// checking for overflow:
1220     ///
1221     /// ```
1222     /// let v = vec![1, 2];
1223     /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1224     ///     x.checked_add(1).ok_or("Overflow!")
1225     /// ).collect();
1226     /// assert_eq!(res, Ok(vec![2, 3]));
1227     /// ```
1228     ///
1229     /// Here is another example that tries to subtract one from another list
1230     /// of integers, this time checking for underflow:
1231     ///
1232     /// ```
1233     /// let v = vec![1, 2, 0];
1234     /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32|
1235     ///     x.checked_sub(1).ok_or("Underflow!")
1236     /// ).collect();
1237     /// assert_eq!(res, Err("Underflow!"));
1238     /// ```
1239     ///
1240     /// Here is a variation on the previous example, showing that no
1241     /// further elements are taken from `iter` after the first `Err`.
1242     ///
1243     /// ```
1244     /// let v = vec![3, 2, 1, 10];
1245     /// let mut shared = 0;
1246     /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|x: &u32| {
1247     ///     shared += x;
1248     ///     x.checked_sub(2).ok_or("Underflow!")
1249     /// }).collect();
1250     /// assert_eq!(res, Err("Underflow!"));
1251     /// assert_eq!(shared, 6);
1252     /// ```
1253     ///
1254     /// Since the third element caused an underflow, no further elements were taken,
1255     /// so the final value of `shared` is 6 (= `3 + 2 + 1`), not 16.
1256     #[inline]
1257     fn from_iter<I: IntoIterator<Item=Result<A, E>>>(iter: I) -> Result<V, E> {
1258         // FIXME(#11084): This could be replaced with Iterator::scan when this
1259         // performance bug is closed.
1260
1261         struct Adapter<Iter, E> {
1262             iter: Iter,
1263             err: Option<E>,
1264         }
1265
1266         impl<T, E, Iter: Iterator<Item=Result<T, E>>> Iterator for Adapter<Iter, E> {
1267             type Item = T;
1268
1269             #[inline]
1270             fn next(&mut self) -> Option<T> {
1271                 match self.iter.next() {
1272                     Some(Ok(value)) => Some(value),
1273                     Some(Err(err)) => {
1274                         self.err = Some(err);
1275                         None
1276                     }
1277                     None => None,
1278                 }
1279             }
1280
1281             fn size_hint(&self) -> (usize, Option<usize>) {
1282                 let (_min, max) = self.iter.size_hint();
1283                 (0, max)
1284             }
1285         }
1286
1287         let mut adapter = Adapter { iter: iter.into_iter(), err: None };
1288         let v: V = FromIterator::from_iter(adapter.by_ref());
1289
1290         match adapter.err {
1291             Some(err) => Err(err),
1292             None => Ok(v),
1293         }
1294     }
1295 }
1296
1297 #[unstable(feature = "try_trait", issue = "42327")]
1298 impl<T,E> ops::Try for Result<T, E> {
1299     type Ok = T;
1300     type Error = E;
1301
1302     #[inline]
1303     fn into_result(self) -> Self {
1304         self
1305     }
1306
1307     #[inline]
1308     fn from_ok(v: T) -> Self {
1309         Ok(v)
1310     }
1311
1312     #[inline]
1313     fn from_error(v: E) -> Self {
1314         Err(v)
1315     }
1316 }