Skip to content

Commit 054c29d

Browse files
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.
2 parents b28a1b2 + bef4ec2 commit 054c29d

File tree

1 file changed

+8
-0
lines changed
  • library/core/src/convert

1 file changed

+8
-0
lines changed

library/core/src/convert/mod.rs

+8
Original file line numberDiff line numberDiff line change
@@ -616,6 +616,14 @@ impl AsRef<str> for str {
616616
}
617617
}
618618

619+
#[stable(feature = "as_mut_str_for_str", since = "1.51.0")]
620+
impl AsMut<str> for str {
621+
#[inline]
622+
fn as_mut(&mut self) -> &mut str {
623+
self
624+
}
625+
}
626+
619627
////////////////////////////////////////////////////////////////////////////////
620628
// THE NO-ERROR ERROR TYPE
621629
////////////////////////////////////////////////////////////////////////////////

0 commit comments

Comments
 (0)