Skip to content

Commit 5cb2fa4

Browse files
committed
Document From trait for Option implementations
1 parent 6318d24 commit 5cb2fa4

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

src/libcore/option.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1357,12 +1357,38 @@ impl<'a, T> IntoIterator for &'a mut Option<T> {
13571357

13581358
#[stable(since = "1.12.0", feature = "option_from")]
13591359
impl<T> From<T> for Option<T> {
1360+
/// Copies val to a new Option::Some
1361+
///
1362+
/// # Examples
1363+
///
1364+
/// ```
1365+
/// let o: Option<u8> = Option::from(67);
1366+
/// assert_eq!(Some(67), o);
1367+
/// ```
13601368
fn from(val: T) -> Option<T> {
13611369
Some(val)
13621370
}
13631371
}
13641372

13651373
#[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
1374+
/// Converts from &Option<T> to Option<&T>
1375+
///
1376+
/// # Examples
1377+
/// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, preserving the original.
1378+
/// The [`map`] method takes the `self` argument by value, consuming the original,
1379+
/// so this technique uses `as_ref` to first take an `Option` to a reference
1380+
/// to the value inside the original.
1381+
///
1382+
/// [`map`]: enum.Option.html#method.map
1383+
/// [`String`]: ../../std/string/struct.String.html
1384+
/// [`usize`]: ../../std/primitive.usize.html
1385+
///
1386+
/// ```
1387+
/// let s: Option<String> = Some(String::from("Hello, Rustaceans!"));
1388+
/// let o: Option<usize> = Option::from(&s).map(|ss: &String| ss.len());
1389+
/// println!("Can still print s: {}", s);
1390+
/// assert_eq!(o, Some(18));
1391+
/// ```
13661392
impl<'a, T> From<&'a Option<T>> for Option<&'a T> {
13671393
fn from(o: &'a Option<T>) -> Option<&'a T> {
13681394
o.as_ref()
@@ -1371,6 +1397,19 @@ impl<'a, T> From<&'a Option<T>> for Option<&'a T> {
13711397

13721398
#[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
13731399
impl<'a, T> From<&'a mut Option<T>> for Option<&'a mut T> {
1400+
/// Converts from &mut Option<T> to Option<&mut T>
1401+
///
1402+
/// # Examples
1403+
///
1404+
/// ```
1405+
/// let mut s = Some(String::from("Hello"));
1406+
/// let o: Option<&mut String> = Option::from(&mut s);
1407+
/// match o {
1408+
/// Some(t) => *t = String::from("Hello, Rustaceans!"),
1409+
/// None => (),
1410+
/// }
1411+
/// assert_eq!(s, Some(String::from("Hello, Rustaceans!")));
1412+
/// ```
13741413
fn from(o: &'a mut Option<T>) -> Option<&'a mut T> {
13751414
o.as_mut()
13761415
}

0 commit comments

Comments
 (0)