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?
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.
A type is a specific category of things or people that have something in common.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With