Skip to content

Commit 9f6a2fd

Browse files
authored
Rollup merge of #99335 - Dav1dde:fromstr-docs, r=JohnTitor
Use split_once in FromStr docs Current implementation: ```rust fn from_str(s: &str) -> Result<Self, Self::Err> { let coords: Vec<&str> = s.trim_matches(|p| p == '(' || p == ')' ) .split(',') .collect(); let x_fromstr = coords[0].parse::<i32>()?; let y_fromstr = coords[1].parse::<i32>()?; Ok(Point { x: x_fromstr, y: y_fromstr }) } ``` Creating the vector is not necessary, `split_once` does the job better. Alternatively we could also remove `trim_matches` with `strip_prefix` and `strip_suffix`: ```rust let (x, y) = s .strip_prefix('(') .and_then(|s| s.strip_suffix(')')) .and_then(|s| s.split_once(',')) .unwrap(); ``` The question is how much 'correctness' is too much and distracts from the example. In a real implementation you would also not unwrap (or originally access the vector without bounds checks), but implementing a custom Error and adding a `From<ParseIntError>` and implementing the `Error` trait adds a lot of code to the example which is not relevant to the `FromStr` trait.
2 parents af13e55 + c1c1abc commit 9f6a2fd

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

library/core/src/str/traits.rs

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -519,12 +519,14 @@ unsafe impl const SliceIndex<str> for ops::RangeToInclusive<usize> {
519519
/// type Err = ParseIntError;
520520
///
521521
/// fn from_str(s: &str) -> Result<Self, Self::Err> {
522-
/// let coords: Vec<&str> = s.trim_matches(|p| p == '(' || p == ')' )
523-
/// .split(',')
524-
/// .collect();
525-
///
526-
/// let x_fromstr = coords[0].parse::<i32>()?;
527-
/// let y_fromstr = coords[1].parse::<i32>()?;
522+
/// let (x, y) = s
523+
/// .strip_prefix('(')
524+
/// .and_then(|s| s.strip_suffix(')'))
525+
/// .and_then(|s| s.split_once(','))
526+
/// .unwrap();
527+
///
528+
/// let x_fromstr = x.parse::<i32>()?;
529+
/// let y_fromstr = y.parse::<i32>()?;
528530
///
529531
/// Ok(Point { x: x_fromstr, y: y_fromstr })
530532
/// }

0 commit comments

Comments
 (0)