Skip to content

Commit 7380b1c

Browse files
committed
std: Add Option.unwrap_or_else and a couple tests
1 parent 2bd87ad commit 7380b1c

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

src/libstd/option.rs

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,15 @@ impl<T> Option<T> {
340340
}
341341
}
342342

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+
343352
/// Applies a function zero or more times until the result is `None`.
344353
#[inline]
345354
pub fn while_some(self, blk: &fn(v: T) -> Option<T>) {
@@ -514,6 +523,44 @@ mod tests {
514523
assert_eq!(i, 11);
515524
}
516525

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+
517564
#[test]
518565
fn test_unwrap_or_zero() {
519566
let some_stuff = Some(42);

0 commit comments

Comments
 (0)