Skip to content

Commit 9c7c232

Browse files
committed
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.
1 parent 56a35bc commit 9c7c232

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

library/core/src/str/traits.rs

+9-5
Original file line numberDiff line numberDiff line change
@@ -507,26 +507,28 @@ unsafe impl const SliceIndex<str> for ops::RangeToInclusive<usize> {
507507
///
508508
/// ```
509509
/// use std::str::FromStr;
510-
/// use std::num::ParseIntError;
511510
///
512511
/// #[derive(Debug, PartialEq)]
513512
/// struct Point {
514513
/// x: i32,
515514
/// y: i32
516515
/// }
517516
///
517+
/// #[derive(Debug, PartialEq, Eq)]
518+
/// struct ParsePointError;
519+
///
518520
/// impl FromStr for Point {
519-
/// type Err = ParseIntError;
521+
/// type Err = ParsePointError;
520522
///
521523
/// fn from_str(s: &str) -> Result<Self, Self::Err> {
522524
/// let (x, y) = s
523525
/// .strip_prefix('(')
524526
/// .and_then(|s| s.strip_suffix(')'))
525527
/// .and_then(|s| s.split_once(','))
526-
/// .unwrap();
528+
/// .ok_or(ParsePointError)?;
527529
///
528-
/// let x_fromstr = x.parse::<i32>()?;
529-
/// let y_fromstr = y.parse::<i32>()?;
530+
/// let x_fromstr = x.parse::<i32>().map_err(|_| ParsePointError)?;
531+
/// let y_fromstr = y.parse::<i32>().map_err(|_| ParsePointError)?;
530532
///
531533
/// Ok(Point { x: x_fromstr, y: y_fromstr })
532534
/// }
@@ -538,6 +540,8 @@ unsafe impl const SliceIndex<str> for ops::RangeToInclusive<usize> {
538540
/// // Implicit calls, through parse
539541
/// assert_eq!("(1,2)".parse(), expected);
540542
/// assert_eq!("(1,2)".parse::<Point>(), expected);
543+
/// // Invalid input string
544+
/// assert!(Point::from_str("(1 2)").is_err());
541545
/// ```
542546
#[stable(feature = "rust1", since = "1.0.0")]
543547
pub trait FromStr: Sized {

0 commit comments

Comments
 (0)