kvarn_async::prelude::compact_str::core::convert

Trait AsMut

1.6.0 · source
pub trait AsMut<T>
where T: ?Sized,
{ // Required method fn as_mut(&mut self) -> &mut T; }
Expand description

Used to do a cheap mutable-to-mutable reference conversion.

This trait is similar to AsRef but used for converting between mutable references. If you need to do a costly conversion it is better to implement From with type &mut T or write a custom function.

Note: This trait must not fail. If the conversion can fail, use a dedicated method which returns an Option<T> or a Result<T, E>.

§Generic Implementations

AsMut auto-dereferences if the inner type is a mutable reference (e.g.: foo.as_mut() will work the same if foo has type &mut Foo or &mut &mut Foo).

Note that due to historic reasons, the above currently does not hold generally for all mutably dereferenceable types, e.g. foo.as_mut() will not work the same as Box::new(foo).as_mut(). Instead, many smart pointers provide an as_mut implementation which simply returns a reference to the pointed-to value (but do not perform a cheap reference-to-reference conversion for that value). However, AsMut::as_mut should not be used for the sole purpose of mutable dereferencing; instead Deref coercion’ can be used:

let mut x = Box::new(5i32);
// Avoid this:
// let y: &mut i32 = x.as_mut();
// Better just write:
let y: &mut i32 = &mut x;

Types which implement DerefMut should consider to add an implementation of AsMut<T> as follows:

impl<T> AsMut<T> for SomeType
where
    <SomeType as Deref>::Target: AsMut<T>,
{
    fn as_mut(&mut self) -> &mut T {
        self.deref_mut().as_mut()
    }
}

§Reflexivity

Ideally, AsMut would be reflexive, i.e. there would be an impl<T: ?Sized> AsMut<T> for T with