jeromefroe/lru-rs

How to access LruCache<&'a str, String> with the key of String?

Closed this issue · 1 comments

wfxr commented

I don't known why but it looks like get requires the argument has the same lifetime as it's key.

use lru::LruCache;
use std::collections::HashMap;

struct Store<'a> {
    index: HashMap<&'a str, String>,
    cache: LruCache<&'a str, String>,
}

impl<'a> Store<'a> {
    // can compile
    fn foo(&mut self, key: String) -> String {
        self.index.get(&key.as_str()).unwrap().to_owned()
    }
    // cannot compile
    fn bar(&mut self, key: String) -> String {
        self.cache.get(&key.as_str()).unwrap().to_owned()
    }
}

How can I get the method bar to compile?

wfxr commented

Sorry for the disturbing. Thanks @marmeladema, I got where the problem is. Just need to remove the extra &:

fn bar(&mut self, key: String) -> String {
    self.cache.get(key.as_str()).unwrap().to_owned()
}