rust

Specify method implementation in impl for trait with shadowing method name


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),
        }
    }
}

Rust playground

I have tried:


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:

    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()
    }