@@ -1357,12 +1357,38 @@ impl<'a, T> IntoIterator for &'a mut Option<T> {
1357
1357
1358
1358
#[ stable( since = "1.12.0" , feature = "option_from" ) ]
1359
1359
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
+ /// ```
1360
1368
fn from ( val : T ) -> Option < T > {
1361
1369
Some ( val)
1362
1370
}
1363
1371
}
1364
1372
1365
1373
#[ 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
+ /// ```
1366
1392
impl < ' a , T > From < & ' a Option < T > > for Option < & ' a T > {
1367
1393
fn from ( o : & ' a Option < T > ) -> Option < & ' a T > {
1368
1394
o. as_ref ( )
@@ -1371,6 +1397,19 @@ impl<'a, T> From<&'a Option<T>> for Option<&'a T> {
1371
1397
1372
1398
#[ stable( feature = "option_ref_from_ref_option" , since = "1.30.0" ) ]
1373
1399
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
+ /// ```
1374
1413
fn from ( o : & ' a mut Option < T > ) -> Option < & ' a mut T > {
1375
1414
o. as_mut ( )
1376
1415
}
0 commit comments