AsRef auto-dereferences if the inner type is a reference or a mutable reference (e.g.: foo.as_ref() will work the same if foo has type &mut Foo or &&mut Foo )
This expression is ambiguous, ... will work the same if ..., the same as what? What is the difference between this behavior and DeRef's auto-dereferencing? I hope there could be a code example explaining about this.
impl<T: ?Sized, U: ?Sized> AsRef<U> for &T
where
T: AsRef<U>,
{
fn as_ref(&self) -> &U {
<T as AsRef<U>>::as_ref(*self)
}
}
impl<T: ?Sized, U: ?Sized> AsRef<U> for &mut T
where
T: AsRef<U>,
{
fn as_ref(&self) -> &U {
<T as AsRef<U>>::as_ref(*self)
}
}
So when you have &T or &mut T, when T: AsRef<U>, both &T and &mut T also impls AsRef<U> (and thus, also &&T, and &mut &&mut &T, etc.). It saves you a dereference, and helps with generics. It is, indeed, very similar to Deref (in fact, it has the same impls), except the fact that with Deref there is another thing: the compiler inserting & and * automatically when you call a method.