Skip to content

Commit bd421e2

Browse files
committed
More practical examples for Result::and_then
1 parent 73a5f01 commit bd421e2

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

library/core/src/result.rs

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1281,16 +1281,22 @@ impl<T, E> Result<T, E> {
12811281
///
12821282
/// # Examples
12831283
///
1284-
/// Basic usage:
1284+
/// ```
1285+
/// fn squared_string(x: u32) -> Result<String, &'static str> {
1286+
/// Ok((x * x).to_string())
1287+
/// }
12851288
///
1289+
/// assert_eq!(Ok(2).and_then(squared_string), Ok(4.to_string()));
1290+
/// assert_eq!(Err("not a number").and_then(squared_string), Err("not a number"));
12861291
/// ```
1287-
/// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
1288-
/// fn err(x: u32) -> Result<u32, u32> { Err(x) }
12891292
///
1290-
/// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
1291-
/// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
1292-
/// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
1293-
/// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
1293+
/// Often used to chain fallible operations that may return [`Err`].
1294+
///
1295+
/// ```
1296+
/// use std::path::Path;
1297+
///
1298+
/// let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified());
1299+
/// assert!(root_modified_time.is_ok())
12941300
/// ```
12951301
#[inline]
12961302
#[stable(feature = "rust1", since = "1.0.0")]

0 commit comments

Comments
 (0)