diff --git a/library/core/src/result.rs b/library/core/src/result.rs index d6d1762572928..33ec0c8f33f73 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -592,6 +592,28 @@ impl Result { } } + /// Maps a `Result` to a `Result` by swapping the success/failure + /// semantics of the stored variant. + /// + /// # Examples + /// + /// Basic usage: + /// + /// ``` + /// #![feature(result_swap)] + /// + /// assert_eq!(Ok("Error :(").swap(), Err("Error :(")); + /// assert_eq!(Err("Success!").swap(), Ok("Success!")); + /// ``` + #[inline] + #[unstable(feature = "result_swap", issue = "none")] + pub fn swap(self) -> Result { + match self { + Ok(t) => Err(t), + Err(e) => Ok(e), + } + } + ///////////////////////////////////////////////////////////////////////// // Iterator constructors ///////////////////////////////////////////////////////////////////////// diff --git a/library/core/tests/lib.rs b/library/core/tests/lib.rs index 98f5982fbb2c1..572db1c74a19b 100644 --- a/library/core/tests/lib.rs +++ b/library/core/tests/lib.rs @@ -76,6 +76,7 @@ #![feature(integer_atomics)] #![feature(slice_group_by)] #![feature(trusted_random_access)] +#![feature(result_swap)] #![deny(unsafe_op_in_unsafe_fn)] extern crate test; diff --git a/library/core/tests/result.rs b/library/core/tests/result.rs index 81660870e95e4..4dc3a0c7f0fcb 100644 --- a/library/core/tests/result.rs +++ b/library/core/tests/result.rs @@ -358,3 +358,10 @@ fn result_opt_conversions() { assert_eq!(res, Err(BadNumErr)) } + +#[test] +fn test_result_swap() { + assert_eq!(Ok::<_, u8>("err").swap(), Err("err")); + assert_eq!(Err::("ok").swap(), Ok("ok")); + assert_eq!(Ok::<_, u8>("ok").swap().swap(), Ok("ok")); +}