Improve FromStr example

The `from_str` implementation from the example had an `unwrap` that would make it panic on invalid input strings. Instead of panicking, it nows returns an error to better reflect the intented behavior of the `FromStr` trait.
This commit is contained in:
Eduardo Sánchez Muñoz 2022-10-02 11:32:56 +02:00
parent 56a35bc906
commit 9c7c232a50

View File

@ -507,7 +507,6 @@ fn index_mut(self, slice: &mut str) -> &mut Self::Output {
/// ///
/// ``` /// ```
/// use std::str::FromStr; /// use std::str::FromStr;
/// use std::num::ParseIntError;
/// ///
/// #[derive(Debug, PartialEq)] /// #[derive(Debug, PartialEq)]
/// struct Point { /// struct Point {
@ -515,18 +514,21 @@ fn index_mut(self, slice: &mut str) -> &mut Self::Output {
/// y: i32 /// y: i32
/// } /// }
/// ///
/// #[derive(Debug, PartialEq, Eq)]
/// struct ParsePointError;
///
/// impl FromStr for Point { /// impl FromStr for Point {
/// type Err = ParseIntError; /// type Err = ParsePointError;
/// ///
/// fn from_str(s: &str) -> Result<Self, Self::Err> { /// fn from_str(s: &str) -> Result<Self, Self::Err> {
/// let (x, y) = s /// let (x, y) = s
/// .strip_prefix('(') /// .strip_prefix('(')
/// .and_then(|s| s.strip_suffix(')')) /// .and_then(|s| s.strip_suffix(')'))
/// .and_then(|s| s.split_once(',')) /// .and_then(|s| s.split_once(','))
/// .unwrap(); /// .ok_or(ParsePointError)?;
/// ///
/// let x_fromstr = x.parse::<i32>()?; /// let x_fromstr = x.parse::<i32>().map_err(|_| ParsePointError)?;
/// let y_fromstr = y.parse::<i32>()?; /// let y_fromstr = y.parse::<i32>().map_err(|_| ParsePointError)?;
/// ///
/// Ok(Point { x: x_fromstr, y: y_fromstr }) /// Ok(Point { x: x_fromstr, y: y_fromstr })
/// } /// }
@ -538,6 +540,8 @@ fn index_mut(self, slice: &mut str) -> &mut Self::Output {
/// // Implicit calls, through parse /// // Implicit calls, through parse
/// assert_eq!("(1,2)".parse(), expected); /// assert_eq!("(1,2)".parse(), expected);
/// assert_eq!("(1,2)".parse::<Point>(), expected); /// assert_eq!("(1,2)".parse::<Point>(), expected);
/// // Invalid input string
/// assert!(Point::from_str("(1 2)").is_err());
/// ``` /// ```
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
pub trait FromStr: Sized { pub trait FromStr: Sized {