String-keyed HashMap in rust?

hashmap, rust

Solution

The declaration of `contains_key_equiv` is:

pub fn contains_key_equiv<Q:Hash + Equiv<K>>(&self, key: &Q) -> bool

That is, it takes a reference to something that is `Equiv`alent to `K == ~str`. So to check for a `&str` (which is `Equiv`alent to `~str`), we want a `& &str` (a reference to a string slice).

map.contains_key_equiv(&("hello"));

// or

map.contains_key_equiv(& &"hello");

(Note that these are equivalent, and are just required to get around the fact that `"foo" == &"foo"` are both `&str`s.)

Problem

I'm having trouble figuring out how to use a HashMap with a key of type `~str` idiomatically. For example, ``` let mut map: hashmap::HashMap<~str, int> = hashmap::HashMap::new(); // Inserting is fine, I just have to copy the string. map.insert("hello".to_str(), 1); // If I look something up, do I really need to copy the string? // This works: map.contains_key(&"hello".to_str()); // This doesn't: as expected, I get // error: mismatched types: expected `&~str` but found `&'static str` (expected &-ptr but found &'static str) map.contains_key("hello"); ``` Based on this bug report, I tried ``` map.contains_key_equiv("hello"); ``` but got ``` error: mismatched types: expected `&<V367>` but found `&'static str` (expected &-ptr but found &'static str) ``` I really don't understand this last message; does anyone have a suggestion?

Original source