PageRenderTime 63ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/src/libcore/result.rs

http://github.com/eholk/rust
Rust | 1110 lines | 322 code | 72 blank | 716 comment | 27 complexity | ade915818cc02cdddccbf9c97784863d MD5 | raw file
Possible License(s): AGPL-1.0, BSD-2-Clause, 0BSD, Apache-2.0, MIT, LGPL-2.0
  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. //! Error handling with the `Result` type.
  11. //!
  12. //! [`Result<T, E>`][`Result`] is the type used for returning and propagating
  13. //! errors. It is an enum with the variants, [`Ok(T)`], representing
  14. //! success and containing a value, and [`Err(E)`], representing error
  15. //! and containing an error value.
  16. //!
  17. //! ```
  18. //! # #[allow(dead_code)]
  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](../../std/io/index.html).
  28. //!
  29. //! A simple function returning [`Result`] might be
  30. //! defined and used like so:
  31. //!
  32. //! ```
  33. //! #[derive(Debug)]
  34. //! enum Version { Version1, Version2 }
  35. //!
  36. //! fn parse_version(header: &[u8]) -> Result<Version, &'static str> {
  37. //! match header.get(0) {
  38. //! None => Err("invalid header length"),
  39. //! Some(&1) => Ok(Version::Version1),
  40. //! Some(&2) => Ok(Version::Version2),
  41. //! Some(_) => Err("invalid version"),
  42. //! }
  43. //! }
  44. //!
  45. //! let version = parse_version(&[1, 2, 3, 4]);
  46. //! match version {
  47. //! Ok(v) => println!("working with version: {:?}", v),
  48. //! Err(e) => println!("error parsing header: {:?}", e),
  49. //! }
  50. //! ```
  51. //!
  52. //! Pattern matching on [`Result`]s is clear and straightforward for
  53. //! simple cases, but [`Result`] comes with some convenience methods
  54. //! that make working with it more succinct.
  55. //!
  56. //! ```
  57. //! let good_result: Result<i32, i32> = Ok(10);
  58. //! let bad_result: Result<i32, i32> = Err(10);
  59. //!
  60. //! // The `is_ok` and `is_err` methods do what they say.
  61. //! assert!(good_result.is_ok() && !good_result.is_err());
  62. //! assert!(bad_result.is_err() && !bad_result.is_ok());
  63. //!
  64. //! // `map` consumes the `Result` and produces another.
  65. //! let good_result: Result<i32, i32> = good_result.map(|i| i + 1);
  66. //! let bad_result: Result<i32, i32> = bad_result.map(|i| i - 1);
  67. //!
  68. //! // Use `and_then` to continue the computation.
  69. //! let good_result: Result<bool, i32> = good_result.and_then(|i| Ok(i == 11));
  70. //!
  71. //! // Use `or_else` to handle the error.
  72. //! let bad_result: Result<i32, i32> = bad_result.or_else(|i| Ok(i + 20));
  73. //!
  74. //! // Consume the result and return the contents with `unwrap`.
  75. //! let final_awesome_result = good_result.unwrap();
  76. //! ```
  77. //!
  78. //! # Results must be used
  79. //!
  80. //! A common problem with using return values to indicate errors is
  81. //! that it is easy to ignore the return value, thus failing to handle
  82. //! the error. [`Result`] is annotated with the `#[must_use]` attribute,
  83. //! which will cause the compiler to issue a warning when a Result
  84. //! value is ignored. This makes [`Result`] especially useful with
  85. //! functions that may encounter errors but don't otherwise return a
  86. //! useful value.
  87. //!
  88. //! Consider the [`write_all`] method defined for I/O types
  89. //! by the [`Write`] trait:
  90. //!
  91. //! ```
  92. //! use std::io;
  93. //!
  94. //! trait Write {
  95. //! fn write_all(&mut self, bytes: &[u8]) -> Result<(), io::Error>;
  96. //! }
  97. //! ```
  98. //!
  99. //! *Note: The actual definition of [`Write`] uses [`io::Result`], which
  100. //! is just a synonym for [`Result`]`<T, `[`io::Error`]`>`.*
  101. //!
  102. //! This method doesn't produce a value, but the write may
  103. //! fail. It's crucial to handle the error case, and *not* write
  104. //! something like this:
  105. //!
  106. //! ```no_run
  107. //! # #![allow(unused_must_use)] // \o/
  108. //! use std::fs::File;
  109. //! use std::io::prelude::*;
  110. //!
  111. //! let mut file = File::create("valuable_data.txt").unwrap();
  112. //! // If `write_all` errors, then we'll never know, because the return
  113. //! // value is ignored.
  114. //! file.write_all(b"important message");
  115. //! ```
  116. //!
  117. //! If you *do* write that in Rust, the compiler will give you a
  118. //! warning (by default, controlled by the `unused_must_use` lint).
  119. //!
  120. //! You might instead, if you don't want to handle the error, simply
  121. //! assert success with [`expect`]. This will panic if the
  122. //! write fails, providing a marginally useful message indicating why:
  123. //!
  124. //! ```{.no_run}
  125. //! use std::fs::File;
  126. //! use std::io::prelude::*;
  127. //!
  128. //! let mut file = File::create("valuable_data.txt").unwrap();
  129. //! file.write_all(b"important message").expect("failed to write message");
  130. //! ```
  131. //!
  132. //! You might also simply assert success:
  133. //!
  134. //! ```{.no_run}
  135. //! # use std::fs::File;
  136. //! # use std::io::prelude::*;
  137. //! # let mut file = File::create("valuable_data.txt").unwrap();
  138. //! assert!(file.write_all(b"important message").is_ok());
  139. //! ```
  140. //!
  141. //! Or propagate the error up the call stack with [`?`]:
  142. //!
  143. //! ```
  144. //! # use std::fs::File;
  145. //! # use std::io::prelude::*;
  146. //! # use std::io;
  147. //! # #[allow(dead_code)]
  148. //! fn write_message() -> io::Result<()> {
  149. //! let mut file = File::create("valuable_data.txt")?;
  150. //! file.write_all(b"important message")?;
  151. //! Ok(())
  152. //! }
  153. //! ```
  154. //!
  155. //! # The `?` syntax
  156. //!
  157. //! When writing code that calls many functions that return the
  158. //! [`Result`] type, the error handling can be tedious. The [`?`]
  159. //! syntax hides some of the boilerplate of propagating errors up the
  160. //! call stack.
  161. //!
  162. //! It replaces this:
  163. //!
  164. //! ```
  165. //! # #![allow(dead_code)]
  166. //! use std::fs::File;
  167. //! use std::io::prelude::*;
  168. //! use std::io;
  169. //!
  170. //! struct Info {
  171. //! name: String,
  172. //! age: i32,
  173. //! rating: i32,
  174. //! }
  175. //!
  176. //! fn write_info(info: &Info) -> io::Result<()> {
  177. //! // Early return on error
  178. //! let mut file = match File::create("my_best_friends.txt") {
  179. //! Err(e) => return Err(e),
  180. //! Ok(f) => f,
  181. //! };
  182. //! if let Err(e) = file.write_all(format!("name: {}\n", info.name).as_bytes()) {
  183. //! return Err(e)
  184. //! }
  185. //! if let Err(e) = file.write_all(format!("age: {}\n", info.age).as_bytes()) {
  186. //! return Err(e)
  187. //! }
  188. //! if let Err(e) = file.write_all(format!("rating: {}\n", info.rating).as_bytes()) {
  189. //! return Err(e)
  190. //! }
  191. //! Ok(())
  192. //! }
  193. //! ```
  194. //!
  195. //! With this:
  196. //!
  197. //! ```
  198. //! # #![allow(dead_code)]
  199. //! use std::fs::File;
  200. //! use std::io::prelude::*;
  201. //! use std::io;
  202. //!
  203. //! struct Info {
  204. //! name: String,
  205. //! age: i32,
  206. //! rating: i32,
  207. //! }
  208. //!
  209. //! fn write_info(info: &Info) -> io::Result<()> {
  210. //! let mut file = File::create("my_best_friends.txt")?;
  211. //! // Early return on error
  212. //! file.write_all(format!("name: {}\n", info.name).as_bytes())?;
  213. //! file.write_all(format!("age: {}\n", info.age).as_bytes())?;
  214. //! file.write_all(format!("rating: {}\n", info.rating).as_bytes())?;
  215. //! Ok(())
  216. //! }
  217. //! ```
  218. //!
  219. //! *It's much nicer!*
  220. //!
  221. //! Ending the expression with [`?`] will result in the unwrapped
  222. //! success ([`Ok`]) value, unless the result is [`Err`], in which case
  223. //! [`Err`] is returned early from the enclosing function.
  224. //!
  225. //! [`?`] can only be used in functions that return [`Result`] because of the
  226. //! early return of [`Err`] that it provides.
  227. //!
  228. //! [`expect`]: enum.Result.html#method.expect
  229. //! [`Write`]: ../../std/io/trait.Write.html
  230. //! [`write_all`]: ../../std/io/trait.Write.html#method.write_all
  231. //! [`io::Result`]: ../../std/io/type.Result.html
  232. //! [`?`]: ../../std/macro.try.html
  233. //! [`Result`]: enum.Result.html
  234. //! [`Ok(T)`]: enum.Result.html#variant.Ok
  235. //! [`Err(E)`]: enum.Result.html#variant.Err
  236. //! [`io::Error`]: ../../std/io/struct.Error.html
  237. //! [`Ok`]: enum.Result.html#variant.Ok
  238. //! [`Err`]: enum.Result.html#variant.Err
  239. #![stable(feature = "rust1", since = "1.0.0")]
  240. use fmt;
  241. use iter::{FromIterator, FusedIterator, TrustedLen};
  242. /// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
  243. ///
  244. /// See the [`std::result`](index.html) module documentation for details.
  245. #[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
  246. #[must_use]
  247. #[stable(feature = "rust1", since = "1.0.0")]
  248. pub enum Result<T, E> {
  249. /// Contains the success value
  250. #[stable(feature = "rust1", since = "1.0.0")]
  251. Ok(#[stable(feature = "rust1", since = "1.0.0")] T),
  252. /// Contains the error value
  253. #[stable(feature = "rust1", since = "1.0.0")]
  254. Err(#[stable(feature = "rust1", since = "1.0.0")] E),
  255. }
  256. /////////////////////////////////////////////////////////////////////////////
  257. // Type implementation
  258. /////////////////////////////////////////////////////////////////////////////
  259. impl<T, E> Result<T, E> {
  260. /////////////////////////////////////////////////////////////////////////
  261. // Querying the contained values
  262. /////////////////////////////////////////////////////////////////////////
  263. /// Returns `true` if the result is `Ok`.
  264. ///
  265. /// # Examples
  266. ///
  267. /// Basic usage:
  268. ///
  269. /// ```
  270. /// let x: Result<i32, &str> = Ok(-3);
  271. /// assert_eq!(x.is_ok(), true);
  272. ///
  273. /// let x: Result<i32, &str> = Err("Some error message");
  274. /// assert_eq!(x.is_ok(), false);
  275. /// ```
  276. #[inline]
  277. #[stable(feature = "rust1", since = "1.0.0")]
  278. pub fn is_ok(&self) -> bool {
  279. match *self {
  280. Ok(_) => true,
  281. Err(_) => false
  282. }
  283. }
  284. /// Returns `true` if the result is `Err`.
  285. ///
  286. /// # Examples
  287. ///
  288. /// Basic usage:
  289. ///
  290. /// ```
  291. /// let x: Result<i32, &str> = Ok(-3);
  292. /// assert_eq!(x.is_err(), false);
  293. ///
  294. /// let x: Result<i32, &str> = Err("Some error message");
  295. /// assert_eq!(x.is_err(), true);
  296. /// ```
  297. #[inline]
  298. #[stable(feature = "rust1", since = "1.0.0")]
  299. pub fn is_err(&self) -> bool {
  300. !self.is_ok()
  301. }
  302. /////////////////////////////////////////////////////////////////////////
  303. // Adapter for each variant
  304. /////////////////////////////////////////////////////////////////////////
  305. /// Converts from `Result<T, E>` to [`Option<T>`].
  306. ///
  307. /// Converts `self` into an [`Option<T>`], consuming `self`,
  308. /// and discarding the error, if any.
  309. ///
  310. /// [`Option<T>`]: ../../std/option/enum.Option.html
  311. ///
  312. /// # Examples
  313. ///
  314. /// Basic usage:
  315. ///
  316. /// ```
  317. /// let x: Result<u32, &str> = Ok(2);
  318. /// assert_eq!(x.ok(), Some(2));
  319. ///
  320. /// let x: Result<u32, &str> = Err("Nothing here");
  321. /// assert_eq!(x.ok(), None);
  322. /// ```
  323. #[inline]
  324. #[stable(feature = "rust1", since = "1.0.0")]
  325. pub fn ok(self) -> Option<T> {
  326. match self {
  327. Ok(x) => Some(x),
  328. Err(_) => None,
  329. }
  330. }
  331. /// Converts from `Result<T, E>` to [`Option<E>`].
  332. ///
  333. /// Converts `self` into an [`Option<E>`], consuming `self`,
  334. /// and discarding the success value, if any.
  335. ///
  336. /// [`Option<E>`]: ../../std/option/enum.Option.html
  337. ///
  338. /// # Examples
  339. ///
  340. /// Basic usage:
  341. ///
  342. /// ```
  343. /// let x: Result<u32, &str> = Ok(2);
  344. /// assert_eq!(x.err(), None);
  345. ///
  346. /// let x: Result<u32, &str> = Err("Nothing here");
  347. /// assert_eq!(x.err(), Some("Nothing here"));
  348. /// ```
  349. #[inline]
  350. #[stable(feature = "rust1", since = "1.0.0")]
  351. pub fn err(self) -> Option<E> {
  352. match self {
  353. Ok(_) => None,
  354. Err(x) => Some(x),
  355. }
  356. }
  357. /////////////////////////////////////////////////////////////////////////
  358. // Adapter for working with references
  359. /////////////////////////////////////////////////////////////////////////
  360. /// Converts from `Result<T, E>` to `Result<&T, &E>`.
  361. ///
  362. /// Produces a new `Result`, containing a reference
  363. /// into the original, leaving the original in place.
  364. ///
  365. /// # Examples
  366. ///
  367. /// Basic usage:
  368. ///
  369. /// ```
  370. /// let x: Result<u32, &str> = Ok(2);
  371. /// assert_eq!(x.as_ref(), Ok(&2));
  372. ///
  373. /// let x: Result<u32, &str> = Err("Error");
  374. /// assert_eq!(x.as_ref(), Err(&"Error"));
  375. /// ```
  376. #[inline]
  377. #[stable(feature = "rust1", since = "1.0.0")]
  378. pub fn as_ref(&self) -> Result<&T, &E> {
  379. match *self {
  380. Ok(ref x) => Ok(x),
  381. Err(ref x) => Err(x),
  382. }
  383. }
  384. /// Converts from `Result<T, E>` to `Result<&mut T, &mut E>`.
  385. ///
  386. /// # Examples
  387. ///
  388. /// Basic usage:
  389. ///
  390. /// ```
  391. /// fn mutate(r: &mut Result<i32, i32>) {
  392. /// match r.as_mut() {
  393. /// Ok(v) => *v = 42,
  394. /// Err(e) => *e = 0,
  395. /// }
  396. /// }
  397. ///
  398. /// let mut x: Result<i32, i32> = Ok(2);
  399. /// mutate(&mut x);
  400. /// assert_eq!(x.unwrap(), 42);
  401. ///
  402. /// let mut x: Result<i32, i32> = Err(13);
  403. /// mutate(&mut x);
  404. /// assert_eq!(x.unwrap_err(), 0);
  405. /// ```
  406. #[inline]
  407. #[stable(feature = "rust1", since = "1.0.0")]
  408. pub fn as_mut(&mut self) -> Result<&mut T, &mut E> {
  409. match *self {
  410. Ok(ref mut x) => Ok(x),
  411. Err(ref mut x) => Err(x),
  412. }
  413. }
  414. /////////////////////////////////////////////////////////////////////////
  415. // Transforming contained values
  416. /////////////////////////////////////////////////////////////////////////
  417. /// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to a
  418. /// contained `Ok` value, leaving an `Err` value untouched.
  419. ///
  420. /// This function can be used to compose the results of two functions.
  421. ///
  422. /// # Examples
  423. ///
  424. /// Print the numbers on each line of a string multiplied by two.
  425. ///
  426. /// ```
  427. /// let line = "1\n2\n3\n4\n";
  428. ///
  429. /// for num in line.lines() {
  430. /// match num.parse::<i32>().map(|i| i * 2) {
  431. /// Ok(n) => println!("{}", n),
  432. /// Err(..) => {}
  433. /// }
  434. /// }
  435. /// ```
  436. #[inline]
  437. #[stable(feature = "rust1", since = "1.0.0")]
  438. pub fn map<U, F: FnOnce(T) -> U>(self, op: F) -> Result<U,E> {
  439. match self {
  440. Ok(t) => Ok(op(t)),
  441. Err(e) => Err(e)
  442. }
  443. }
  444. /// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to a
  445. /// contained `Err` value, leaving an `Ok` value untouched.
  446. ///
  447. /// This function can be used to pass through a successful result while handling
  448. /// an error.
  449. ///
  450. /// # Examples
  451. ///
  452. /// Basic usage:
  453. ///
  454. /// ```
  455. /// fn stringify(x: u32) -> String { format!("error code: {}", x) }
  456. ///
  457. /// let x: Result<u32, u32> = Ok(2);
  458. /// assert_eq!(x.map_err(stringify), Ok(2));
  459. ///
  460. /// let x: Result<u32, u32> = Err(13);
  461. /// assert_eq!(x.map_err(stringify), Err("error code: 13".to_string()));
  462. /// ```
  463. #[inline]
  464. #[stable(feature = "rust1", since = "1.0.0")]
  465. pub fn map_err<F, O: FnOnce(E) -> F>(self, op: O) -> Result<T,F> {
  466. match self {
  467. Ok(t) => Ok(t),
  468. Err(e) => Err(op(e))
  469. }
  470. }
  471. /////////////////////////////////////////////////////////////////////////
  472. // Iterator constructors
  473. /////////////////////////////////////////////////////////////////////////
  474. /// Returns an iterator over the possibly contained value.
  475. ///
  476. /// The iterator yields one value if the result is [`Ok`], otherwise none.
  477. ///
  478. /// # Examples
  479. ///
  480. /// Basic usage:
  481. ///
  482. /// ```
  483. /// let x: Result<u32, &str> = Ok(7);
  484. /// assert_eq!(x.iter().next(), Some(&7));
  485. ///
  486. /// let x: Result<u32, &str> = Err("nothing!");
  487. /// assert_eq!(x.iter().next(), None);
  488. /// ```
  489. ///
  490. /// [`Ok`]: enum.Result.html#variant.Ok
  491. #[inline]
  492. #[stable(feature = "rust1", since = "1.0.0")]
  493. pub fn iter(&self) -> Iter<T> {
  494. Iter { inner: self.as_ref().ok() }
  495. }
  496. /// Returns a mutable iterator over the possibly contained value.
  497. ///
  498. /// The iterator yields one value if the result is [`Ok`], otherwise none.
  499. ///
  500. /// # Examples
  501. ///
  502. /// Basic usage:
  503. ///
  504. /// ```
  505. /// let mut x: Result<u32, &str> = Ok(7);
  506. /// match x.iter_mut().next() {
  507. /// Some(v) => *v = 40,
  508. /// None => {},
  509. /// }
  510. /// assert_eq!(x, Ok(40));
  511. ///
  512. /// let mut x: Result<u32, &str> = Err("nothing!");
  513. /// assert_eq!(x.iter_mut().next(), None);
  514. /// ```
  515. ///
  516. /// [`Ok`]: enum.Result.html#variant.Ok
  517. #[inline]
  518. #[stable(feature = "rust1", since = "1.0.0")]
  519. pub fn iter_mut(&mut self) -> IterMut<T> {
  520. IterMut { inner: self.as_mut().ok() }
  521. }
  522. ////////////////////////////////////////////////////////////////////////
  523. // Boolean operations on the values, eager and lazy
  524. /////////////////////////////////////////////////////////////////////////
  525. /// Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`.
  526. ///
  527. /// # Examples
  528. ///
  529. /// Basic usage:
  530. ///
  531. /// ```
  532. /// let x: Result<u32, &str> = Ok(2);
  533. /// let y: Result<&str, &str> = Err("late error");
  534. /// assert_eq!(x.and(y), Err("late error"));
  535. ///
  536. /// let x: Result<u32, &str> = Err("early error");
  537. /// let y: Result<&str, &str> = Ok("foo");
  538. /// assert_eq!(x.and(y), Err("early error"));
  539. ///
  540. /// let x: Result<u32, &str> = Err("not a 2");
  541. /// let y: Result<&str, &str> = Err("late error");
  542. /// assert_eq!(x.and(y), Err("not a 2"));
  543. ///
  544. /// let x: Result<u32, &str> = Ok(2);
  545. /// let y: Result<&str, &str> = Ok("different result type");
  546. /// assert_eq!(x.and(y), Ok("different result type"));
  547. /// ```
  548. #[inline]
  549. #[stable(feature = "rust1", since = "1.0.0")]
  550. pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
  551. match self {
  552. Ok(_) => res,
  553. Err(e) => Err(e),
  554. }
  555. }
  556. /// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
  557. ///
  558. /// This function can be used for control flow based on `Result` values.
  559. ///
  560. /// # Examples
  561. ///
  562. /// Basic usage:
  563. ///
  564. /// ```
  565. /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
  566. /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
  567. ///
  568. /// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
  569. /// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
  570. /// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
  571. /// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
  572. /// ```
  573. #[inline]
  574. #[stable(feature = "rust1", since = "1.0.0")]
  575. pub fn and_then<U, F: FnOnce(T) -> Result<U, E>>(self, op: F) -> Result<U, E> {
  576. match self {
  577. Ok(t) => op(t),
  578. Err(e) => Err(e),
  579. }
  580. }
  581. /// Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`.
  582. ///
  583. /// # Examples
  584. ///
  585. /// Basic usage:
  586. ///
  587. /// ```
  588. /// let x: Result<u32, &str> = Ok(2);
  589. /// let y: Result<u32, &str> = Err("late error");
  590. /// assert_eq!(x.or(y), Ok(2));
  591. ///
  592. /// let x: Result<u32, &str> = Err("early error");
  593. /// let y: Result<u32, &str> = Ok(2);
  594. /// assert_eq!(x.or(y), Ok(2));
  595. ///
  596. /// let x: Result<u32, &str> = Err("not a 2");
  597. /// let y: Result<u32, &str> = Err("late error");
  598. /// assert_eq!(x.or(y), Err("late error"));
  599. ///
  600. /// let x: Result<u32, &str> = Ok(2);
  601. /// let y: Result<u32, &str> = Ok(100);
  602. /// assert_eq!(x.or(y), Ok(2));
  603. /// ```
  604. #[inline]
  605. #[stable(feature = "rust1", since = "1.0.0")]
  606. pub fn or<F>(self, res: Result<T, F>) -> Result<T, F> {
  607. match self {
  608. Ok(v) => Ok(v),
  609. Err(_) => res,
  610. }
  611. }
  612. /// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
  613. ///
  614. /// This function can be used for control flow based on result values.
  615. ///
  616. /// # Examples
  617. ///
  618. /// Basic usage:
  619. ///
  620. /// ```
  621. /// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
  622. /// fn err(x: u32) -> Result<u32, u32> { Err(x) }
  623. ///
  624. /// assert_eq!(Ok(2).or_else(sq).or_else(sq), Ok(2));
  625. /// assert_eq!(Ok(2).or_else(err).or_else(sq), Ok(2));
  626. /// assert_eq!(Err(3).or_else(sq).or_else(err), Ok(9));
  627. /// assert_eq!(Err(3).or_else(err).or_else(err), Err(3));
  628. /// ```
  629. #[inline]
  630. #[stable(feature = "rust1", since = "1.0.0")]
  631. pub fn or_else<F, O: FnOnce(E) -> Result<T, F>>(self, op: O) -> Result<T, F> {
  632. match self {
  633. Ok(t) => Ok(t),
  634. Err(e) => op(e),
  635. }
  636. }
  637. /// Unwraps a result, yielding the content of an `Ok`.
  638. /// Else, it returns `optb`.
  639. ///
  640. /// # Examples
  641. ///
  642. /// Basic usage:
  643. ///
  644. /// ```
  645. /// let optb = 2;
  646. /// let x: Result<u32, &str> = Ok(9);
  647. /// assert_eq!(x.unwrap_or(optb), 9);
  648. ///
  649. /// let x: Result<u32, &str> = Err("error");
  650. /// assert_eq!(x.unwrap_or(optb), optb);
  651. /// ```
  652. #[inline]
  653. #[stable(feature = "rust1", since = "1.0.0")]
  654. pub fn unwrap_or(self, optb: T) -> T {
  655. match self {
  656. Ok(t) => t,
  657. Err(_) => optb
  658. }
  659. }
  660. /// Unwraps a result, yielding the content of an `Ok`.
  661. /// If the value is an `Err` then it calls `op` with its value.
  662. ///
  663. /// # Examples
  664. ///
  665. /// Basic usage:
  666. ///
  667. /// ```
  668. /// fn count(x: &str) -> usize { x.len() }
  669. ///
  670. /// assert_eq!(Ok(2).unwrap_or_else(count), 2);
  671. /// assert_eq!(Err("foo").unwrap_or_else(count), 3);
  672. /// ```
  673. #[inline]
  674. #[stable(feature = "rust1", since = "1.0.0")]
  675. pub fn unwrap_or_else<F: FnOnce(E) -> T>(self, op: F) -> T {
  676. match self {
  677. Ok(t) => t,
  678. Err(e) => op(e)
  679. }
  680. }
  681. }
  682. impl<T, E: fmt::Debug> Result<T, E> {
  683. /// Unwraps a result, yielding the content of an `Ok`.
  684. ///
  685. /// # Panics
  686. ///
  687. /// Panics if the value is an `Err`, with a panic message provided by the
  688. /// `Err`'s value.
  689. ///
  690. /// # Examples
  691. ///
  692. /// Basic usage:
  693. ///
  694. /// ```
  695. /// let x: Result<u32, &str> = Ok(2);
  696. /// assert_eq!(x.unwrap(), 2);
  697. /// ```
  698. ///
  699. /// ```{.should_panic}
  700. /// let x: Result<u32, &str> = Err("emergency failure");
  701. /// x.unwrap(); // panics with `emergency failure`
  702. /// ```
  703. #[inline]
  704. #[stable(feature = "rust1", since = "1.0.0")]
  705. pub fn unwrap(self) -> T {
  706. match self {
  707. Ok(t) => t,
  708. Err(e) => unwrap_failed("called `Result::unwrap()` on an `Err` value", e),
  709. }
  710. }
  711. /// Unwraps a result, yielding the content of an `Ok`.
  712. ///
  713. /// # Panics
  714. ///
  715. /// Panics if the value is an `Err`, with a panic message including the
  716. /// passed message, and the content of the `Err`.
  717. ///
  718. /// # Examples
  719. ///
  720. /// Basic usage:
  721. ///
  722. /// ```{.should_panic}
  723. /// let x: Result<u32, &str> = Err("emergency failure");
  724. /// x.expect("Testing expect"); // panics with `Testing expect: emergency failure`
  725. /// ```
  726. #[inline]
  727. #[stable(feature = "result_expect", since = "1.4.0")]
  728. pub fn expect(self, msg: &str) -> T {
  729. match self {
  730. Ok(t) => t,
  731. Err(e) => unwrap_failed(msg, e),
  732. }
  733. }
  734. }
  735. impl<T: fmt::Debug, E> Result<T, E> {
  736. /// Unwraps a result, yielding the content of an `Err`.
  737. ///
  738. /// # Panics
  739. ///
  740. /// Panics if the value is an `Ok`, with a custom panic message provided
  741. /// by the `Ok`'s value.
  742. ///
  743. /// # Examples
  744. ///
  745. /// ```{.should_panic}
  746. /// let x: Result<u32, &str> = Ok(2);
  747. /// x.unwrap_err(); // panics with `2`
  748. /// ```
  749. ///
  750. /// ```
  751. /// let x: Result<u32, &str> = Err("emergency failure");
  752. /// assert_eq!(x.unwrap_err(), "emergency failure");
  753. /// ```
  754. #[inline]
  755. #[stable(feature = "rust1", since = "1.0.0")]
  756. pub fn unwrap_err(self) -> E {
  757. match self {
  758. Ok(t) => unwrap_failed("called `Result::unwrap_err()` on an `Ok` value", t),
  759. Err(e) => e,
  760. }
  761. }
  762. /// Unwraps a result, yielding the content of an `Err`.
  763. ///
  764. /// # Panics
  765. ///
  766. /// Panics if the value is an `Ok`, with a panic message including the
  767. /// passed message, and the content of the `Ok`.
  768. ///
  769. /// # Examples
  770. ///
  771. /// Basic usage:
  772. ///
  773. /// ```{.should_panic}
  774. /// let x: Result<u32, &str> = Ok(10);
  775. /// x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10`
  776. /// ```
  777. #[inline]
  778. #[stable(feature = "result_expect_err", since = "1.17.0")]
  779. pub fn expect_err(self, msg: &str) -> E {
  780. match self {
  781. Ok(t) => unwrap_failed(msg, t),
  782. Err(e) => e,
  783. }
  784. }
  785. }
  786. impl<T: Default, E> Result<T, E> {
  787. /// Returns the contained value or a default
  788. ///
  789. /// Consumes the `self` argument then, if `Ok`, returns the contained
  790. /// value, otherwise if `Err`, returns the default value for that
  791. /// type.
  792. ///
  793. /// # Examples
  794. ///
  795. /// Convert a string to an integer, turning poorly-formed strings
  796. /// into 0 (the default value for integers). [`parse`] converts
  797. /// a string to any other type that implements [`FromStr`], returning an
  798. /// `Err` on error.
  799. ///
  800. /// ```
  801. /// let good_year_from_input = "1909";
  802. /// let bad_year_from_input = "190blarg";
  803. /// let good_year = good_year_from_input.parse().unwrap_or_default();
  804. /// let bad_year = bad_year_from_input.parse().unwrap_or_default();
  805. ///
  806. /// assert_eq!(1909, good_year);
  807. /// assert_eq!(0, bad_year);
  808. /// ```
  809. ///
  810. /// [`parse`]: ../../std/primitive.str.html#method.parse
  811. /// [`FromStr`]: ../../std/str/trait.FromStr.html
  812. #[inline]
  813. #[stable(feature = "result_unwrap_or_default", since = "1.16.0")]
  814. pub fn unwrap_or_default(self) -> T {
  815. match self {
  816. Ok(x) => x,
  817. Err(_) => Default::default(),
  818. }
  819. }
  820. }
  821. // This is a separate function to reduce the code size of the methods
  822. #[inline(never)]
  823. #[cold]
  824. fn unwrap_failed<E: fmt::Debug>(msg: &str, error: E) -> ! {
  825. panic!("{}: {:?}", msg, error)
  826. }
  827. /////////////////////////////////////////////////////////////////////////////
  828. // Trait implementations
  829. /////////////////////////////////////////////////////////////////////////////
  830. #[stable(feature = "rust1", since = "1.0.0")]
  831. impl<T, E> IntoIterator for Result<T, E> {
  832. type Item = T;
  833. type IntoIter = IntoIter<T>;
  834. /// Returns a consuming iterator over the possibly contained value.
  835. ///
  836. /// The iterator yields one value if the result is [`Ok`], otherwise none.
  837. ///
  838. /// # Examples
  839. ///
  840. /// Basic usage:
  841. ///
  842. /// ```
  843. /// let x: Result<u32, &str> = Ok(5);
  844. /// let v: Vec<u32> = x.into_iter().collect();
  845. /// assert_eq!(v, [5]);
  846. ///
  847. /// let x: Result<u32, &str> = Err("nothing!");
  848. /// let v: Vec<u32> = x.into_iter().collect();
  849. /// assert_eq!(v, []);
  850. /// ```
  851. ///
  852. /// [`Ok`]: enum.Result.html#variant.Ok
  853. #[inline]
  854. fn into_iter(self) -> IntoIter<T> {
  855. IntoIter { inner: self.ok() }
  856. }
  857. }
  858. #[stable(since = "1.4.0", feature = "result_iter")]
  859. impl<'a, T, E> IntoIterator for &'a Result<T, E> {
  860. type Item = &'a T;
  861. type IntoIter = Iter<'a, T>;
  862. fn into_iter(self) -> Iter<'a, T> {
  863. self.iter()
  864. }
  865. }
  866. #[stable(since = "1.4.0", feature = "result_iter")]
  867. impl<'a, T, E> IntoIterator for &'a mut Result<T, E> {
  868. type Item = &'a mut T;
  869. type IntoIter = IterMut<'a, T>;
  870. fn into_iter(mut self) -> IterMut<'a, T> {
  871. self.iter_mut()
  872. }
  873. }
  874. /////////////////////////////////////////////////////////////////////////////
  875. // The Result Iterators
  876. /////////////////////////////////////////////////////////////////////////////
  877. /// An iterator over a reference to the [`Ok`] variant of a [`Result`].
  878. ///
  879. /// The iterator yields one value if the result is [`Ok`], otherwise none.
  880. ///
  881. /// Created by [`Result::iter`].
  882. ///
  883. /// [`Ok`]: enum.Result.html#variant.Ok
  884. /// [`Result`]: enum.Result.html
  885. /// [`Result::iter`]: enum.Result.html#method.iter
  886. #[derive(Debug)]
  887. #[stable(feature = "rust1", since = "1.0.0")]
  888. pub struct Iter<'a, T: 'a> { inner: Option<&'a T> }
  889. #[stable(feature = "rust1", since = "1.0.0")]
  890. impl<'a, T> Iterator for Iter<'a, T> {
  891. type Item = &'a T;
  892. #[inline]
  893. fn next(&mut self) -> Option<&'a T> { self.inner.take() }
  894. #[inline]
  895. fn size_hint(&self) -> (usize, Option<usize>) {
  896. let n = if self.inner.is_some() {1} else {0};
  897. (n, Some(n))
  898. }
  899. }
  900. #[stable(feature = "rust1", since = "1.0.0")]
  901. impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
  902. #[inline]
  903. fn next_back(&mut self) -> Option<&'a T> { self.inner.take() }
  904. }
  905. #[stable(feature = "rust1", since = "1.0.0")]
  906. impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
  907. #[unstable(feature = "fused", issue = "35602")]
  908. impl<'a, T> FusedIterator for Iter<'a, T> {}
  909. #[unstable(feature = "trusted_len", issue = "37572")]
  910. unsafe impl<'a, A> TrustedLen for Iter<'a, A> {}
  911. #[stable(feature = "rust1", since = "1.0.0")]
  912. impl<'a, T> Clone for Iter<'a, T> {
  913. fn clone(&self) -> Iter<'a, T> { Iter { inner: self.inner } }
  914. }
  915. /// An iterator over a mutable reference to the [`Ok`] variant of a [`Result`].
  916. ///
  917. /// Created by [`Result::iter_mut`].
  918. ///
  919. /// [`Ok`]: enum.Result.html#variant.Ok
  920. /// [`Result`]: enum.Result.html
  921. /// [`Result::iter_mut`]: enum.Result.html#method.iter_mut
  922. #[derive(Debug)]
  923. #[stable(feature = "rust1", since = "1.0.0")]
  924. pub struct IterMut<'a, T: 'a> { inner: Option<&'a mut T> }
  925. #[stable(feature = "rust1", since = "1.0.0")]
  926. impl<'a, T> Iterator for IterMut<'a, T> {
  927. type Item = &'a mut T;
  928. #[inline]
  929. fn next(&mut self) -> Option<&'a mut T> { self.inner.take() }
  930. #[inline]
  931. fn size_hint(&self) -> (usize, Option<usize>) {
  932. let n = if self.inner.is_some() {1} else {0};
  933. (n, Some(n))
  934. }
  935. }
  936. #[stable(feature = "rust1", since = "1.0.0")]
  937. impl<'a, T> DoubleEndedIterator for IterMut<'a, T> {
  938. #[inline]
  939. fn next_back(&mut self) -> Option<&'a mut T> { self.inner.take() }
  940. }
  941. #[stable(feature = "rust1", since = "1.0.0")]
  942. impl<'a, T> ExactSizeIterator for IterMut<'a, T> {}
  943. #[unstable(feature = "fused", issue = "35602")]
  944. impl<'a, T> FusedIterator for IterMut<'a, T> {}
  945. #[unstable(feature = "trusted_len", issue = "37572")]
  946. unsafe impl<'a, A> TrustedLen for IterMut<'a, A> {}
  947. /// An iterator over the value in a [`Ok`] variant of a [`Result`].
  948. ///
  949. /// The iterator yields one value if the result is [`Ok`], otherwise none.
  950. ///
  951. /// This struct is created by the [`into_iter`] method on
  952. /// [`Result`][`Result`] (provided by the [`IntoIterator`] trait).
  953. ///
  954. /// [`Ok`]: enum.Result.html#variant.Ok
  955. /// [`Result`]: enum.Result.html
  956. /// [`into_iter`]: ../iter/trait.IntoIterator.html#tymethod.into_iter
  957. /// [`IntoIterator`]: ../iter/trait.IntoIterator.html
  958. #[derive(Debug)]
  959. #[stable(feature = "rust1", since = "1.0.0")]
  960. pub struct IntoIter<T> { inner: Option<T> }
  961. #[stable(feature = "rust1", since = "1.0.0")]
  962. impl<T> Iterator for IntoIter<T> {
  963. type Item = T;
  964. #[inline]
  965. fn next(&mut self) -> Option<T> { self.inner.take() }
  966. #[inline]
  967. fn size_hint(&self) -> (usize, Option<usize>) {
  968. let n = if self.inner.is_some() {1} else {0};
  969. (n, Some(n))
  970. }
  971. }
  972. #[stable(feature = "rust1", since = "1.0.0")]
  973. impl<T> DoubleEndedIterator for IntoIter<T> {
  974. #[inline]
  975. fn next_back(&mut self) -> Option<T> { self.inner.take() }
  976. }
  977. #[stable(feature = "rust1", since = "1.0.0")]
  978. impl<T> ExactSizeIterator for IntoIter<T> {}
  979. #[unstable(feature = "fused", issue = "35602")]
  980. impl<T> FusedIterator for IntoIter<T> {}
  981. #[unstable(feature = "trusted_len", issue = "37572")]
  982. unsafe impl<A> TrustedLen for IntoIter<A> {}
  983. /////////////////////////////////////////////////////////////////////////////
  984. // FromIterator
  985. /////////////////////////////////////////////////////////////////////////////
  986. #[stable(feature = "rust1", since = "1.0.0")]
  987. impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
  988. /// Takes each element in the `Iterator`: if it is an `Err`, no further
  989. /// elements are taken, and the `Err` is returned. Should no `Err` occur, a
  990. /// container with the values of each `Result` is returned.
  991. ///
  992. /// Here is an example which increments every integer in a vector,
  993. /// checking for overflow:
  994. ///
  995. /// ```
  996. /// use std::u32;
  997. ///
  998. /// let v = vec![1, 2];
  999. /// let res: Result<Vec<u32>, &'static str> = v.iter().map(|&x: &u32|
  1000. /// if x == u32::MAX { Err("Overflow!") }
  1001. /// else { Ok(x + 1) }
  1002. /// ).collect();
  1003. /// assert!(res == Ok(vec![2, 3]));
  1004. /// ```
  1005. #[inline]
  1006. fn from_iter<I: IntoIterator<Item=Result<A, E>>>(iter: I) -> Result<V, E> {
  1007. // FIXME(#11084): This could be replaced with Iterator::scan when this
  1008. // performance bug is closed.
  1009. struct Adapter<Iter, E> {
  1010. iter: Iter,
  1011. err: Option<E>,
  1012. }
  1013. impl<T, E, Iter: Iterator<Item=Result<T, E>>> Iterator for Adapter<Iter, E> {
  1014. type Item = T;
  1015. #[inline]
  1016. fn next(&mut self) -> Option<T> {
  1017. match self.iter.next() {
  1018. Some(Ok(value)) => Some(value),
  1019. Some(Err(err)) => {
  1020. self.err = Some(err);
  1021. None
  1022. }
  1023. None => None,
  1024. }
  1025. }
  1026. fn size_hint(&self) -> (usize, Option<usize>) {
  1027. let (_min, max) = self.iter.size_hint();
  1028. (0, max)
  1029. }
  1030. }
  1031. let mut adapter = Adapter { iter: iter.into_iter(), err: None };
  1032. let v: V = FromIterator::from_iter(adapter.by_ref());
  1033. match adapter.err {
  1034. Some(err) => Err(err),
  1035. None => Ok(v),
  1036. }
  1037. }
  1038. }