Why double-dereferencing?

Code from lib/rustlib/src/rust/library/core/src/borrow.rs:

#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> Borrow<T> for &mut T {
    fn borrow(&self) -> &T {
        &**self
    }
}

I don't understand why double-dereferencing ( double asterisks ) is used here. What is the reason behind this? Any reading/video explaining this?

Just checking the types:

  • self here is of type &Self, i.e. &&mut T;
  • *self is &mut T;
  • **self is T;
  • so, &**self is &T, which is what return type requires.
8 Likes

Thank you @Cerber-Ursi for the explanation. But why did you make &Self and &&mut T identical? My understanding is that &Self is &mut T. Where the second referencing comes from?

Nope, Self is &mut T because the impl is ... for &mut T. Thus &Self is &&mut T.

1 Like

I see. Thank you.

Self is always the type you are impling for. A generic type placeholder can stand for anything – if you are impling for a reference, then it will stand for a reference. Rust's type system is uniform and consistent like that.

1 Like

Thank you. That's clear.

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.