std: Add Option.{result_or_default,or_default} that uses Default

This commit is contained in:
Erick Tryzelaar 2013-09-09 19:32:32 -07:00
parent f1374a7044
commit e6c11313c8
3 changed files with 23 additions and 3 deletions

View File

@ -173,7 +173,7 @@ pub fn check_pat_variant(pcx: &pat_ctxt, pat: @ast::Pat, path: &ast::Path,
fcx.write_error(pat.id); fcx.write_error(pat.id);
kind_name = "[error]"; kind_name = "[error]";
arg_types = (*subpats).clone() arg_types = (*subpats).clone()
.unwrap_or(~[]) .unwrap_or_default()
.map(|_| ty::mk_err()); .map(|_| ty::mk_err());
} }
} }
@ -222,7 +222,7 @@ pub fn check_pat_variant(pcx: &pat_ctxt, pat: @ast::Pat, path: &ast::Path,
fcx.write_error(pat.id); fcx.write_error(pat.id);
kind_name = "[error]"; kind_name = "[error]";
arg_types = (*subpats).clone() arg_types = (*subpats).clone()
.unwrap_or(~[]) .unwrap_or_default()
.map(|_| ty::mk_err()); .map(|_| ty::mk_err());
} }
} }

View File

@ -350,6 +350,26 @@ impl<T> Option<T> {
} }
} }
impl<T: Default> Option<T> {
/// Returns the contained value or default (for this type)
#[inline]
pub fn unwrap_or_default(self) -> T {
match self {
Some(x) => x,
None => Default::default()
}
}
/// Returns self or `Some`-wrapped default value
#[inline]
pub fn or_default(self) -> Option<T> {
match self {
None => Some(Default::default()),
x => x,
}
}
}
impl<T> Default for Option<T> { impl<T> Default for Option<T> {
fn default() -> Option<T> { None } fn default() -> Option<T> { None }
} }

View File

@ -3461,7 +3461,7 @@ impl Parser {
let ident = self.parse_ident(); let ident = self.parse_ident();
let opt_bounds = self.parse_optional_ty_param_bounds(); let opt_bounds = self.parse_optional_ty_param_bounds();
// For typarams we don't care about the difference b/w "<T>" and "<T:>". // For typarams we don't care about the difference b/w "<T>" and "<T:>".
let bounds = opt_bounds.unwrap_or(opt_vec::Empty); let bounds = opt_bounds.unwrap_or_default();
ast::TyParam { ident: ident, id: ast::DUMMY_NODE_ID, bounds: bounds } ast::TyParam { ident: ident, id: ast::DUMMY_NODE_ID, bounds: bounds }
} }