Rollup merge of #80279 - Yaulendil:str-as-mut, r=m-ou-se

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.
This commit is contained in:
Jonas Schievink 2021-01-31 01:47:23 +01:00 committed by GitHub
commit 054c29d22c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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
////////////////////////////////////////////////////////////////////////////////