Skip to content

Commit bb9b2e0

Browse files
committed
auto merge of #13475 : Ryman/rust/result_unwrap_or_else, r=brson
It might make more sense to mirror `Option`'s `unwrap_or_else` but I've left it as `handle` as it feels more explicit about the signature difference.
2 parents 5d284a0 + a16eae6 commit bb9b2e0

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

src/libstd/result.rs

+61
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,26 @@ impl<T, E> Result<T, E> {
188188
}
189189
}
190190

191+
/// Unwraps a result, yielding the content of an `Ok`.
192+
/// Else it returns `optb`.
193+
#[inline]
194+
pub fn unwrap_or(self, optb: T) -> T {
195+
match self {
196+
Ok(t) => t,
197+
Err(_) => optb
198+
}
199+
}
200+
201+
/// Unwraps a result, yielding the content of an `Ok`.
202+
/// If the value is an `Err` then it calls `op` with its value.
203+
#[inline]
204+
pub fn unwrap_or_handle(self, op: |E| -> T) -> T {
205+
match self {
206+
Ok(t) => t,
207+
Err(e) => op(e)
208+
}
209+
}
210+
191211
/// Unwraps a result, yielding the content of an `Err`.
192212
/// Fails if the value is an `Ok`.
193213
#[inline]
@@ -389,4 +409,45 @@ mod tests {
389409
assert_eq!(format!("{}", ok), ~"Ok(100)");
390410
assert_eq!(format!("{}", err), ~"Err(Err)");
391411
}
412+
413+
#[test]
414+
pub fn test_unwrap_or() {
415+
let ok: Result<int, ~str> = Ok(100);
416+
let ok_err: Result<int, ~str> = Err(~"Err");
417+
418+
assert_eq!(ok.unwrap_or(50), 100);
419+
assert_eq!(ok_err.unwrap_or(50), 50);
420+
}
421+
422+
#[test]
423+
pub fn test_unwrap_or_else() {
424+
fn handler(msg: ~str) -> int {
425+
if msg == ~"I got this." {
426+
50
427+
} else {
428+
fail!("BadBad")
429+
}
430+
}
431+
432+
let ok: Result<int, ~str> = Ok(100);
433+
let ok_err: Result<int, ~str> = Err(~"I got this.");
434+
435+
assert_eq!(ok.unwrap_or_handle(handler), 100);
436+
assert_eq!(ok_err.unwrap_or_handle(handler), 50);
437+
}
438+
439+
#[test]
440+
#[should_fail]
441+
pub fn test_unwrap_or_else_failure() {
442+
fn handler(msg: ~str) -> int {
443+
if msg == ~"I got this." {
444+
50
445+
} else {
446+
fail!("BadBad")
447+
}
448+
}
449+
450+
let bad_err: Result<int, ~str> = Err(~"Unrecoverable mess.");
451+
let _ : int = bad_err.unwrap_or_handle(handler);
452+
}
392453
}

0 commit comments

Comments
 (0)