Skip to content

Commit

Permalink
Rollup merge of #80279 - Yaulendil:str-as-mut, r=m-ou-se
Browse files Browse the repository at this point in the history
Implement missing `AsMut<str>` for `str`

Allows `&mut str` to be taken by a Generic which requires `T` such that `T: AsMut<str>`. Motivating example:

```rust
impl<'i, T> From<T> for StructImmut<'i> where
    T: AsRef<str> + 'i,
{
    fn from(asref: T) -> Self {
        let string: &str = asref.as_ref();
        //  ...
    }
}

impl<'i, T> From<T> for StructMut<'i> where
    T: AsMut<str> + 'i,
{
    fn from(mut asmut: T) -> Self {
        let string: &mut str = asmut.as_mut();
        //  ...
    }
}
```

The Immutable form of this structure can be constructed by `StructImmut::from(s)` where `s` may be a `&String` or a `&str`, because `AsRef<str>` is implemented for `str`. However, the mutable form of the structure can be constructed in the same way **only** with a `&mut String`, and **not** with a `&mut str`.

This change does have some precedent, because as can be seen in [the Implementors](https://doc.rust-lang.org/std/convert/trait.AsMut.html#implementors), `AsMut<[T]>` is implemented for `[T]` as well as for `Vec<T>`, but `AsMut<str>` is implemented only for `String`. This would complete the symmetry.

As a trait implementation, this should be immediately stable.
  • Loading branch information
jonas-schievink committed Jan 31, 2021
2 parents b28a1b2 + bef4ec2 commit 054c29d
Showing 1 changed file with 8 additions and 0 deletions.
8 changes: 8 additions & 0 deletions library/core/src/convert/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -616,6 +616,14 @@ impl AsRef<str> for str {
}
}

#[stable(feature = "as_mut_str_for_str", since = "1.51.0")]
impl AsMut<str> for str {
#[inline]
fn as_mut(&mut self) -> &mut str {
self
}
}

////////////////////////////////////////////////////////////////////////////////
// THE NO-ERROR ERROR TYPE
////////////////////////////////////////////////////////////////////////////////
Expand Down

0 comments on commit 054c29d

Please sign in to comment.