File tree 1 file changed +20
-0
lines changed
1 file changed +20
-0
lines changed Original file line number Diff line number Diff line change @@ -49,6 +49,7 @@ use option;
49
49
use ptr;
50
50
use str;
51
51
use util;
52
+ use num:: Zero ;
52
53
53
54
/// The option type
54
55
#[ deriving_eq]
@@ -170,6 +171,12 @@ pub pure fn is_some<T>(opt: &Option<T>) -> bool {
170
171
!is_none ( opt)
171
172
}
172
173
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
+
173
180
pub pure fn get_default < T : Copy > ( opt : Option < T > , def : T ) -> T {
174
181
//! Returns the contained value or a default
175
182
@@ -333,6 +340,11 @@ impl<T: Copy> Option<T> {
333
340
}
334
341
}
335
342
343
+ impl < T : Copy Zero > Option < T > {
344
+ #[ inline( always) ]
345
+ pure fn get_zero ( self ) -> T { get_zero ( self ) }
346
+ }
347
+
336
348
#[ test]
337
349
fn test_unwrap_ptr ( ) {
338
350
let x = ~0 ;
@@ -407,6 +419,14 @@ fn test_option_while_some() {
407
419
assert i == 11 ;
408
420
}
409
421
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
+
410
430
// Local Variables:
411
431
// mode: rust;
412
432
// fill-column: 78;
You can’t perform that action at this time.
0 commit comments