`&**self`的类型是什么?
我正在阅读std::vec::Vec实现并遇到了这个:
Index::index(&**self, index)
https://doc.rust-lang.org/src/alloc/vec.rs.html#1939
我知道那self是类型&Vec,因此*self是Vec。&**self在这种情况下是什么类型?
回答
self是 type &Vec<T>,*self也是Vec<T>,正如你所说。*对于非参考类型等效于利用其Deref然后解除引用,所以**self是*上一个Vec<T>,这将调用Deref,并成为一个[T],其被引用时,把它变成一个&[T]。
基本上,这是一种复杂的编写方式.as_slice()。你可以自己看看这个:
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();
}
游乐场链接