Result::and_then: show type conversion

This commit is contained in:
cyqsimon 2022-02-12 12:19:03 +08:00
parent 7eaecc6508
commit adfac00f45
No known key found for this signature in database
GPG key ID: 1D8CE2F297390D65

View file

@ -1282,14 +1282,13 @@ pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
/// # Examples /// # Examples
/// ///
/// ``` /// ```
/// fn sq(x: u32) -> Result<u32, &'static str> { /// fn sq_then_to_string(x: u32) -> Result<String, &'static str> {
/// x.checked_mul(x).ok_or("overflowed") /// x.checked_mul(x).map(|sq| sq.to_string()).ok_or("overflowed")
/// } /// }
/// ///
/// assert_eq!(Ok(2).and_then(sq), Ok(4)); /// assert_eq!(Ok(2).and_then(sq_then_to_string), Ok(4.to_string()));
/// assert_eq!(Ok(1_000_000).and_then(sq), Err("overflowed")); /// assert_eq!(Ok(1_000_000).and_then(sq_then_to_string), Err("overflowed"));
/// assert_eq!(Err("not a number").and_then(sq), Err("not a number")); /// assert_eq!(Err("not a number").and_then(sq_then_to_string), Err("not a number"));
/// ``` /// ```
/// ///
/// Often used to chain fallible operations that may return [`Err`]. /// Often used to chain fallible operations that may return [`Err`].