What does `AsRef` auto-dereference do?

From AsRef's std document:

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.

In Rust code, that means these two impls (mod.rs - source):

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.

1 Like

Replying directly to the question:

Means, "foo can be &mut Foo or &&mut Foo, and in both these cases this will work the same".

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.