From 9c7c232a50819ef2bfb59eae283a5e7ed70dd952 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eduardo=20S=C3=A1nchez=20Mu=C3=B1oz?= Date: Sun, 2 Oct 2022 11:32:56 +0200 Subject: [PATCH] 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. --- library/core/src/str/traits.rs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/library/core/src/str/traits.rs b/library/core/src/str/traits.rs index 18f2ce6edc722..d3ed811b1575b 100644 --- a/library/core/src/str/traits.rs +++ b/library/core/src/str/traits.rs @@ -507,7 +507,6 @@ unsafe impl const SliceIndex for ops::RangeToInclusive { /// /// ``` /// use std::str::FromStr; -/// use std::num::ParseIntError; /// /// #[derive(Debug, PartialEq)] /// struct Point { @@ -515,18 +514,21 @@ unsafe impl const SliceIndex for ops::RangeToInclusive { /// y: i32 /// } /// +/// #[derive(Debug, PartialEq, Eq)] +/// struct ParsePointError; +/// /// impl FromStr for Point { -/// type Err = ParseIntError; +/// type Err = ParsePointError; /// /// fn from_str(s: &str) -> Result { /// let (x, y) = s /// .strip_prefix('(') /// .and_then(|s| s.strip_suffix(')')) /// .and_then(|s| s.split_once(',')) -/// .unwrap(); +/// .ok_or(ParsePointError)?; /// -/// let x_fromstr = x.parse::()?; -/// let y_fromstr = y.parse::()?; +/// let x_fromstr = x.parse::().map_err(|_| ParsePointError)?; +/// let y_fromstr = y.parse::().map_err(|_| ParsePointError)?; /// /// Ok(Point { x: x_fromstr, y: y_fromstr }) /// } @@ -538,6 +540,8 @@ unsafe impl const SliceIndex for ops::RangeToInclusive { /// // Implicit calls, through parse /// assert_eq!("(1,2)".parse(), expected); /// assert_eq!("(1,2)".parse::(), expected); +/// // Invalid input string +/// assert!(Point::from_str("(1 2)").is_err()); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub trait FromStr: Sized {