How do I get a value from a `HashMap::<&'static str, u32>` using a String as the key?

Viewed 234

With a HashMap::<&'static str, u32>, how do I get a value from an owned String?

Playground

use std::collections::HashMap;

fn main() {
    let mut map = HashMap::<&'static str, u32>::new();
    
    let s = "foo".to_string();
    
    map.insert("foo", 12);
    map.insert("bar", 42);
    
    println!("foo={}", map.get(&s).unwrap());
    println!("bar={}", map.get("bar").unwrap());
}
error[E0277]: the trait bound `&str: Borrow<String>` is not satisfied
  --> src/main.rs:11:28
   |
11 |     println!("foo={}", map.get(&s).unwrap());
   |                            ^^^ the trait `Borrow<String>` is not implemented for `&str`

Using a &'static str directly works:

println!("foo={}", map.get("foo").unwrap());

Strangely, inserting a &str from the owned String also works:

let s = "foo".to_string();
map.insert(&s, 12);

I think that's only because Rust can tell the map doesn't outlive the string, change it to a static map and the borrow checker rightly complains.

1 Answers

Use &s[..] to convert the String into a &str:

println!("foo={}", map.get(&s[..]).unwrap());

(playground)

Related