Skip to content

Commit 056067b

Browse files
committed
add Result::{value, into_value}
1 parent 3adedb8 commit 056067b

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

library/core/src/result.rs

+41
Original file line numberDiff line numberDiff line change
@@ -1212,6 +1212,47 @@ impl<T, E> Result<Result<T, E>, E> {
12121212
}
12131213
}
12141214

1215+
impl<T> Result<T, T> {
1216+
/// Gets a reference to the contained value, requiring that the `Ok` and
1217+
/// `Err` variants have the same type.
1218+
///
1219+
/// # Examples
1220+
/// ```
1221+
/// #![feature(result_value)]
1222+
///
1223+
/// let x: Result<u8, u8> = Ok(1);
1224+
/// assert_eq!(*x.value(), 1);
1225+
/// let y: Result<u32, u32> = Err(42);
1226+
/// assert_eq!(*y.value(), 42);
1227+
/// ```
1228+
#[inline]
1229+
#[unstable(feature = "result_value", issue = "none")]
1230+
pub fn value(&self) -> &T {
1231+
match self {
1232+
Ok(ref t) | Err(ref t) => t,
1233+
}
1234+
}
1235+
1236+
/// Consumes the Result, returning the contained value. This requires that the `Ok` and `Err`
1237+
/// variant have the same type. This can be useful when a function returns a `Result` with the
1238+
/// same information on both variants, e.g.
1239+
/// [`binary_search`](../../std/primitive.slice.html#method.binary_search)
1240+
///
1241+
/// # Examples
1242+
/// #![feature(result_value)]
1243+
///
1244+
/// let slice = &[1, 2, 4, 5, 7];
1245+
/// assert_eq(slice.binary_search(3).into_value(), slice.binary_search(4).into_value());
1246+
/// ```
1247+
#[inline]
1248+
#[unstable(feature = "result_value", issue = "none")]
1249+
pub fn into_value(self) -> T {
1250+
match self {
1251+
Ok(t) | Err(t) => t,
1252+
}
1253+
}
1254+
}
1255+
12151256
// This is a separate function to reduce the code size of the methods
12161257
#[inline(never)]
12171258
#[cold]

0 commit comments

Comments
 (0)