What is the type of `&**self`?

Viewed 145
1 Answers

self is type &Vec<T>, so *self is Vec<T>, as you said. * for non-reference types is equivalent to taking its Deref then dereferencing, so **self is * on a Vec<T>, which will invoke Deref and become a [T], which is referenced, turning it into a &[T].

Basically, it's a complicated way to write .as_slice(). You can see this yourself:

trait Foo {
    fn foo(&self);
}

impl<T> Foo for Vec<T> {
    fn foo(&self) {
        let a: &[T] = &**self;
        let b: &[T] = self; // implicit deref coercion of references
        let c: &[T] = self.as_slice();
        // all of them are the same exact slice in the same region of memory
        assert_eq!(a as *const [T], b as *const [T]);
        assert_eq!(b as *const [T], c as *const [T]);
    }
}

fn main() {
    vec![1, 2, 3].foo();
}

Playground link

Related