Skip to content

Commit

Permalink
Rollup merge of #99335 - Dav1dde:fromstr-docs, r=JohnTitor
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
Dylan-DPC authored Jul 19, 2022
2 parents af13e55 + c1c1abc commit 9f6a2fd
Showing 1 changed file with 8 additions and 6 deletions.
14 changes: 8 additions & 6 deletions library/core/src/str/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -519,12 +519,14 @@ unsafe impl const SliceIndex<str> for ops::RangeToInclusive<usize> {
/// type Err = ParseIntError;
///
/// 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>()?;
/// let (x, y) = s
/// .strip_prefix('(')
/// .and_then(|s| s.strip_suffix(')'))
/// .and_then(|s| s.split_once(','))
/// .unwrap();
///
/// let x_fromstr = x.parse::<i32>()?;
/// let y_fromstr = y.parse::<i32>()?;
///
/// Ok(Point { x: x_fromstr, y: y_fromstr })
/// }
Expand Down

0 comments on commit 9f6a2fd

Please sign in to comment.