Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

I'm reading std::vec::Vec implementation and came across this:

Index::index(&**self, index)

https://doc.rust-lang.org/src/alloc/vec.rs.html#1939

I understand that self is of type &Vec, therefore *self is Vec. What is the type of &**self in this case?

like image 587
Nowibananatzki Avatar asked Jan 02 '21 00:01

Nowibananatzki


People also ask

What is type and examples?

Type is defined as to produce words on a typewriter or computer. An example of type is to write a novel in Microsoft Word. verb.

What means a type?

A type is a specific category of things or people that have something in common.

What is the typeof operator?

The typeof operator is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand.

What is typeof in TypeScript?

TypeScript adds a typeof operator you can use in a type context to refer to the type of a variable or property: let s = "hello"; let n : typeof s ; let n: string. This isn't very useful for basic types, but combined with other type operators, you can use typeof to conveniently express many patterns.


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

like image 112
Aplet123 Avatar answered Oct 19 '22 16:10

Aplet123