Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
More practical examples for Result::and_then
  • Loading branch information
cyqsimon committed Feb 10, 2022
commit bd421e2880d3c67ce77c3286d933be8171d0aaa9
20 changes: 13 additions & 7 deletions library/core/src/result.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1281,16 +1281,22 @@ impl<T, E> Result<T, E> {
///
/// # Examples
///
/// Basic usage:
/// ```
/// fn squared_string(x: u32) -> Result<String, &'static str> {
/// Ok((x * x).to_string())
/// }
///
/// assert_eq!(Ok(2).and_then(squared_string), Ok(4.to_string()));
/// assert_eq!(Err("not a number").and_then(squared_string), Err("not a number"));
/// ```
/// fn sq(x: u32) -> Result<u32, u32> { Ok(x * x) }
/// fn err(x: u32) -> Result<u32, u32> { Err(x) }
///
/// assert_eq!(Ok(2).and_then(sq).and_then(sq), Ok(16));
/// assert_eq!(Ok(2).and_then(sq).and_then(err), Err(4));
/// assert_eq!(Ok(2).and_then(err).and_then(sq), Err(2));
/// assert_eq!(Err(3).and_then(sq).and_then(sq), Err(3));
/// Often used to chain fallible operations that may return [`Err`].
///
/// ```
/// use std::path::Path;
///
/// let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified());
/// assert!(root_modified_time.is_ok())
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
Expand Down