Skip to content

Commit 8e71c21

Browse files
committed
Add option::get_zero
as per rust-lang#3797
1 parent 9e2a59d commit 8e71c21

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

src/libcore/option.rs

+20
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ use option;
4949
use ptr;
5050
use str;
5151
use util;
52+
use num::Zero;
5253

5354
/// The option type
5455
#[deriving_eq]
@@ -170,6 +171,12 @@ pub pure fn is_some<T>(opt: &Option<T>) -> bool {
170171
!is_none(opt)
171172
}
172173

174+
pub pure fn get_zero<T: Copy Zero>(opt: Option<T>) -> T {
175+
//! Returns the contained value or zero (for this type)
176+
177+
match opt { Some(copy x) => x, None => Zero::zero() }
178+
}
179+
173180
pub pure fn get_default<T: Copy>(opt: Option<T>, def: T) -> T {
174181
//! Returns the contained value or a default
175182
@@ -333,6 +340,11 @@ impl<T: Copy> Option<T> {
333340
}
334341
}
335342

343+
impl<T: Copy Zero> Option<T> {
344+
#[inline(always)]
345+
pure fn get_zero(self) -> T { get_zero(self) }
346+
}
347+
336348
#[test]
337349
fn test_unwrap_ptr() {
338350
let x = ~0;
@@ -407,6 +419,14 @@ fn test_option_while_some() {
407419
assert i == 11;
408420
}
409421

422+
#[test]
423+
fn test_get_zero() {
424+
let some_stuff = Some(42);
425+
assert some_stuff.get_zero() == 42;
426+
let no_stuff: Option<int> = None;
427+
assert no_stuff.get_zero() == 0;
428+
}
429+
410430
// Local Variables:
411431
// mode: rust;
412432
// fill-column: 78;

0 commit comments

Comments
 (0)