Dereferencing usize Values from a HashMap

I have two different structures: a HashMap with a signature of HashMap<String, usize>, and a Vector with a signature of Vec<Token>, where Token is a custom struct that I made for a project that I'm working on. In order to retrieve the correct Token from the vector, I use this function:

fn get_opt(&self, o: &str) -> Option<&Token> {
    let opt_name = String::from(o);
    if let Some(index) = self.opts.get(&opt_name) {
    } else {

However, when I compile my project, I receive this error:

error: mismatched types:
 expected `usize`,
    found `&usize`
(expected usize,
    found &-ptr)

And while I would normally just dereference the variable that I'm using, Rust doesn't allow you to dereference a usize. How should I go about solving this?

Finally, before you ask the obvious question "Why not just store the Token within the HashMap and call it a day?", the answer is a little long-winded and complicated. The short answer is to reduce redundancy. There are other Collections within the project that used to store clones of the same Tokens found within the Vector. I decided that it would be better off to store the index of that particular Token, rather than the Token itself.

For the error you posted, try if let Some(&index) instead of Some(index). The & there will match the reference and leave index a plain usize rather than &usize.

Another way you could do it is self.tokens.get(*index) rather than .get(index). This is just another way to turn the &usize into a usize, this time using the * dereference operator.

1 Like