How does the impl of AsRef<Path> for PathBuf work?

Viewed 788

Here is the implementation that I see in my version of Rust:

#[stable(feature = "rust1", since = "1.0.0")]
impl AsRef<Path> for PathBuf {
    #[inline]
    fn as_ref(&self) -> &Path {
        self
    }
}

It says that the implementation for converting a &PathBuf to a &Path is simply to return self, which implies that &PathBuf is &Path (or that the compiler itself knows that they can be converted automatically)?

These are 2 different structs right? How does the compiler know that this is okay?

1 Answers

This is a case of type coercion, which you can read about here.

First, the self in fn as_ref() is a valid "coercion site" because it is a function result. The compiler will try to coerce from the type of self (&PathBuf) to the return type (&Path).

Second, type coercion can occur because the case "&T to &U if T implements Deref<Target = U>" (see the docs) applies here: PathBuf implements Deref<Target=Path>.

So what happens is that the compiler implicitly coerces self from &PathBuf to &Path via Deref.

Related