about summary refs log tree commit diff
diff options
context:
space:
mode:
authorDolpheyn <farissufyan99@gmail.com>2020-05-04 22:14:25 +0800
committerDolpheyn <farissufyan99@gmail.com>2020-05-05 07:27:43 +0800
commit5cb2fa487bf6405a18c13041bc18544884f603a7 (patch)
treebee64bfe8bd39cb0a7c4891fe73ffa8fe654b52a
parent6318d24ad8440fa30428b405be1174478e9536e3 (diff)
downloadrust-5cb2fa487bf6405a18c13041bc18544884f603a7.tar.gz
rust-5cb2fa487bf6405a18c13041bc18544884f603a7.zip
Document From trait for Option implementations
-rw-r--r--src/libcore/option.rs39
1 files changed, 39 insertions, 0 deletions
diff --git a/src/libcore/option.rs b/src/libcore/option.rs
index 63a5277100f..a87f3c1804c 100644
--- a/src/libcore/option.rs
+++ b/src/libcore/option.rs
@@ -1357,12 +1357,38 @@ impl<'a, T> IntoIterator for &'a mut Option<T> {
 
 #[stable(since = "1.12.0", feature = "option_from")]
 impl<T> From<T> for Option<T> {
+    /// Copies val to a new Option::Some
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// let o: Option<u8> = Option::from(67);
+    /// assert_eq!(Some(67), o);
+    /// ```
     fn from(val: T) -> Option<T> {
         Some(val)
     }
 }
 
 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
+    /// Converts from &Option<T> to Option<&T>
+    ///
+    /// # Examples
+    /// Converts an `Option<`[`String`]`>` into an `Option<`[`usize`]`>`, preserving the original.
+    /// The [`map`] method takes the `self` argument by value, consuming the original,
+    /// so this technique uses `as_ref` to first take an `Option` to a reference
+    /// to the value inside the original.
+    ///
+    /// [`map`]: enum.Option.html#method.map
+    /// [`String`]: ../../std/string/struct.String.html
+    /// [`usize`]: ../../std/primitive.usize.html
+    ///
+    /// ```
+    /// let s: Option<String> = Some(String::from("Hello, Rustaceans!"));
+    /// let o: Option<usize> = Option::from(&s).map(|ss: &String| ss.len());
+    /// println!("Can still print s: {}", s);
+    /// assert_eq!(o, Some(18));
+    /// ```
 impl<'a, T> From<&'a Option<T>> for Option<&'a T> {
     fn from(o: &'a Option<T>) -> Option<&'a T> {
         o.as_ref()
@@ -1371,6 +1397,19 @@ impl<'a, T> From<&'a Option<T>> for Option<&'a T> {
 
 #[stable(feature = "option_ref_from_ref_option", since = "1.30.0")]
 impl<'a, T> From<&'a mut Option<T>> for Option<&'a mut T> {
+    /// Converts from &mut Option<T> to Option<&mut T>
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// let mut s = Some(String::from("Hello"));
+    /// let o: Option<&mut String> = Option::from(&mut s);
+    /// match o {
+    ///     Some(t) => *t = String::from("Hello, Rustaceans!"),
+    ///     None => (),
+    /// }
+    /// assert_eq!(s, Some(String::from("Hello, Rustaceans!")));
+    /// ```
     fn from(o: &'a mut Option<T>) -> Option<&'a mut T> {
         o.as_mut()
     }