Skip to content
Permalink
Browse files

core: impl<T> From<T> for Option<T>

Improves ergonomics for functions that have optional parameters: instead
of taking `Option<T>`, they can take a type bounded by
`Into<Option<T>>`.
  • Loading branch information...
kamalmarhubi committed Jan 26, 2016
1 parent eceb96b commit d923734bb1aa7b61545b844deb7bde00efa8566f
Showing with 33 additions and 0 deletions.
  1. +8 −0 src/libcore/option.rs
  2. +25 −0 src/libcoretest/option.rs
@@ -147,6 +147,7 @@ use self::Option::*;

use clone::Clone;
use cmp::{Eq, Ord};
use convert::From;
use default::Default;
use iter::ExactSizeIterator;
use iter::{Iterator, DoubleEndedIterator, FromIterator, IntoIterator};
@@ -715,6 +716,13 @@ impl<T> Default for Option<T> {
fn default() -> Option<T> { None }
}

#[unstable(feature = "option_from", issue = "12345", reason = "recently added")]
impl<T> From<T> for Option<T> {
fn from(t: T) -> Option<T> {
Some(t)
}
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T> IntoIterator for Option<T> {
type Item = T;
@@ -270,3 +270,28 @@ fn test_cloned() {
assert_eq!(opt_ref_ref.clone().cloned(), Some(&val));
assert_eq!(opt_ref_ref.cloned().cloned(), Some(1u32));
}

#[test]
fn test_from() {
assert_eq!(Some(3), Option::from(3));
}

#[test]
fn test_into_optional_parameters() {
use core::convert::Into;
fn myfunc<T, U, V>(t: T, u: U, v: V) -> Option<u8>
where T: Into<Option<u8>>,
U: Into<Option<u8>>,
V: Into<Option<u8>> {
match (t.into() ,u.into(), v.into()) {
(Some(t), Some(u), Some(v)) => Some(t + u + v),
_ => None,
}
}

assert_eq!(None, myfunc(None, 2, 3));
assert_eq!(None, myfunc(1, None, 3));
assert_eq!(None, myfunc(1, 2, None));
assert_eq!(Some(6), myfunc(1, 2, 3));
assert_eq!(Some(6), myfunc(Some(1), Some(2), Some(3)));
}

0 comments on commit d923734

Please sign in to comment.
You can’t perform that action at this time.