Given the following trait + impl block, how can I call std::vec::Vec
's get
method from the implementation for MyMap
's get
method?
trait MyMap<K, V> {
fn get(&self, key: &K) -> Option<&V>;
}
impl<V> MyMap<usize, V> for Vec<Option<V>> {
fn get(&self, key: &usize) -> Option<&V> {
match Vec::get(self, *key).expect("undersized map") {
None => None,
Some(v) => Some(&v),
}
}
}
I have tried:
self.get(*key).expect...
which makes the compiler resolve MyMap
's get and complain about the types being mismatched.Vec::get(self, *key).expect...
, which confusingly resolves MyMap
's get again, with the same errors as self.get
<Self as Vec>::get(self, *key).expect...
which makes the compiler complain about get
not existing at all.Vec
's get
in a fn outside of the impl block, which does work but looks highly suspect and seems like the wrong solution.The get()
isn't implemented directly on Vec
. Instead, it's a method on slices. So the easiest option is to first dereference your vector, yielding a slice, and then call get()
on that slice:
impl<V> MyMap<usize, V> for Vec<Option<V>> {
fn get(&self, key: &usize) -> Option<&V> {
match (**self).get(*key).expect("undersized map") {
None => None,
Some(v) => Some(&v),
}
}
}
Since self
has the type &Vec<...>
we need to dereference twice to get a slice:
Vec<Option<V>>
.Deref
implementation on the vector and yields a [Option<V>]
.As a side note, the method body can be simplified using the Option::as_ref()
method:
fn get(&self, key: &usize) -> Option<&V> {
(**self).get(*key).expect("undersized map").as_ref()
}