Rust-phf: Is there a way to uses non-static str keys for lookup

Hi,

In Maps created by rust-phf only values with a static lifetime can be used as key:

pub struct Map<K: 'static, V: 'static> { /* fields omitted */ }

I'm wondering if there is a way to use get with a non-static key. It seems the signature of get doesn't require a static lifetime, but the compiler still rejects my attempt to use a non-static str:

490 | fn combined_phf(input: &Vec<&str>){
    |                        ---------- help: add explicit lifetime `'static` to the type of `input`: `&std::vec::Vec<&'static str>`
...
493 |         result += EVENTS.get(x).unwrap();
    |                          ^^^ lifetime `'static` required

Note that the type you give to get doesn't need to match exactly the key type, as long as it's possible to Borrow the key as a given type.

Can you share more code, so that we know what's the type of key in the map and what's the type of x you're attempting to use here?

edit Seems that the example in phf's readme showcases getting using non-static str, so it should work, I guess?

Sure, the definition of the Map is this:

static EVENTS: phf::Map<&'static str, u32> = phf_map! {
    "Debugger.breakpointResolved" => 0,
    "Debugger.paused" => 1,
    // etc.
}

And x is &str, and also could be String (but phf doesn't accept String as key definition in the macro because it is not 'static (I think)).

x will come from JSON data that I receive from the network.

Would any other information be relevant in this scenario?

This looks almost exactly like the case from the README (I've edited previous comment and added a link), it should work. The error is very weird... Please share the whole code if possible or provide a link to the playground.

Btw, are you sure x is &str and not &&str or &String? Wild guess – try get(*x).

2 Likes

Btw, are you sure x is &str and not &&str or &String ? Wild guess – try get(*x) .

You are right! :slight_smile:

I saw the example, and thought that there is something that I don't get... :laughing:

Plus, the error message seems a bit misleading (or at least could be more helpful).

Thank you for your help! :slight_smile: