Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify method implementation in impl for trait with shadowing method name

Tags:

rust

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:

  • Hoping the compiler can infer from my types, as they are different: self.get(*key).expect... which makes the compiler resolve MyMap's get and complain about the types being mismatched.
  • Qualifying the type name: Vec::get(self, *key).expect..., which confusingly resolves MyMap's get again, with the same errors as self.get
  • Using Fully qualified syntax: <Self as Vec>::get(self, *key).expect... which makes the compiler complain about get not existing at all.
  • Wrapping Vec's get in a fn outside of the impl block, which does work but looks highly suspect and seems like the wrong solution.
like image 348
Abex Avatar asked May 02 '26 17:05

Abex


1 Answers

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:

  • By dereferencing once, we get a Vec<Option<V>>.
  • Dereferencing again uses the 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()
}
like image 161
Sven Marnach Avatar answered May 05 '26 10:05

Sven Marnach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!