@@ -188,6 +188,26 @@ impl<T, E> Result<T, E> {
188
188
}
189
189
}
190
190
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
+
191
211
/// Unwraps a result, yielding the content of an `Err`.
192
212
/// Fails if the value is an `Ok`.
193
213
#[ inline]
@@ -389,4 +409,45 @@ mod tests {
389
409
assert_eq!(format!(" { } ", ok), ~" Ok ( 100 ) ");
390
410
assert_eq!(format!(" { } ", err), ~" Err ( Err ) ");
391
411
}
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
+ }
392
453
}
0 commit comments