@@ -340,6 +340,15 @@ impl<T> Option<T> {
340
340
}
341
341
}
342
342
343
+ /// Returns the contained value or computes it from a closure
344
+ #[ inline]
345
+ pub fn unwrap_or_else ( self , f : & fn ( ) -> T ) -> T {
346
+ match self {
347
+ Some ( x) => x,
348
+ None => f ( )
349
+ }
350
+ }
351
+
343
352
/// Applies a function zero or more times until the result is `None`.
344
353
#[ inline]
345
354
pub fn while_some ( self , blk : & fn ( v : T ) -> Option < T > ) {
@@ -514,6 +523,44 @@ mod tests {
514
523
assert_eq ! ( i, 11 ) ;
515
524
}
516
525
526
+ #[ test]
527
+ fn test_unwrap ( ) {
528
+ assert_eq ! ( Some ( 1 ) . unwrap( ) , 1 ) ;
529
+ assert_eq ! ( Some ( ~"hello").unwrap(), ~" hello") ;
530
+ }
531
+
532
+ #[ test]
533
+ #[ should_fail]
534
+ fn test_unwrap_fail1( ) {
535
+ let x: Option <int> = None ;
536
+ x. unwrap( ) ;
537
+ }
538
+
539
+ #[ test]
540
+ #[ should_fail]
541
+ fn test_unwrap_fail2( ) {
542
+ let x: Option <~str > = None ;
543
+ x. unwrap( ) ;
544
+ }
545
+
546
+ #[ test]
547
+ fn test_unwrap_or( ) {
548
+ let x: Option <int> = Some ( 1 ) ;
549
+ assert_eq!( x. unwrap_or( 2 ) , 1 ) ;
550
+
551
+ let x: Option <int> = None ;
552
+ assert_eq!( x. unwrap_or( 2 ) , 2 ) ;
553
+ }
554
+
555
+ #[ test]
556
+ fn test_unwrap_or_else( ) {
557
+ let x: Option <int> = Some ( 1 ) ;
558
+ assert_eq!( x. unwrap_or_else( || 2 ) , 1 ) ;
559
+
560
+ let x: Option <int> = None ;
561
+ assert_eq!( x. unwrap_or_else( || 2 ) , 2 ) ;
562
+ }
563
+
517
564
#[ test]
518
565
fn test_unwrap_or_zero( ) {
519
566
let some_stuff = Some ( 42 ) ;
0 commit comments