12

I'm trying to understand how HashMaps work in Rust and I have come up with this example.

use std::collections::HashMap;

fn main() {
    let mut roman2number: HashMap<&'static str, i32> = HashMap::new();
    roman2number.insert("X", 10);
    roman2number.insert("I", 1);

    let roman_num = "XXI".to_string();
    let r0 = roman_num.chars().take(1).collect::<String>();
    let r1: &str = &r0.to_string();
    println!("{:?}", roman2number.get(r1)); // This works

    // println!("{:?}", roman2number.get(&r0.to_string())); // This doesn't
}

When I try to compile the code with last line uncommented, I get the following error

error: the trait bound `&str: std::borrow::Borrow<std::string::String>` is not satisfied [E0277]
println!("{:?}", roman2number.get(&r0.to_string()));
                                            ^~~
note: in this expansion of format_args!
note: in this expansion of print! (defined in <std macros>)
note: in this expansion of println! (defined in <std macros>)
help: run `rustc --explain E0277` to see a detailed explanation

The Trait implementation section of the docs gives the dereferencing as fn deref(&self) -> &str

So what is happening here?

  • I think it's wrong (of whomever authored HashMap::get) to use the Borrow trait here. Basically the generic bound says: you can pass a reference to any type to get, if the key-type is borrowable as that type. It should actually be: you can pass any type to get, as long as that type is coercible to the key-type. But we can't fix this backwards compatibly :( – oli_obk May 30 '16 at 8:52
10

The error is caused by that generic function HashMap::get over String is selected by the compiler during type inference. But you want HashMap::get over str.

So just change

println!("{:?}", roman2number.get(&r0.to_string()));

to

println!("{:?}", roman2number.get::<str>(&r0.to_string()));

to make it explicit. This helps the compiler to select the right function.

Check out Playground here.

It looks to me that coercion Deref<Target> can only happen when we know the target type, so when compiler is trying to infer which HashMap::get to use, it sees &r0.to_string() as type &String but never &str. And &'static str does not implement Borrow<String>. This results a type error. When we specify HashMap::get::<str>, this function expects &str, when coercion can be applied to &String to get a matching &str.

You can check out Deref coercion and String Deref for more details.

  • Thanks. That makes sense. However, wouldn't it mean that Dref has two implementations? One returning &str and other &String? The document doesn't say anything about &String. Am I missing something here? – skanur May 30 '16 at 10:45
  • String only implements Deref<Target=str>. This implementation makes it possible to coerce &String into &str where $str is expected. See Deref coercion. – WiSaGaN May 30 '16 at 11:15
5

The other answers are correct, but I wanted to point out that you have an unneeded to_string (you've already collected into a String) and an alternate way of coercing to a &str, using as:

let r0: String = roman_num.chars().take(1).collect();
println!("{:?}", roman2number.get(&r0 as &str));

In this case, I'd probably just rewrite the map to contain char as the key though:

use std::collections::HashMap;

fn main() {
    let mut roman2number = HashMap::new();
    roman2number.insert('X', 10);
    roman2number.insert('I', 1);

    let roman_num = "XXI";
    for c in roman_num.chars() {
        println!("{:?}", roman2number.get(&c));
    }
}

Note there's no need to have an explicit type for the map, it will be inferred.

  • 1
    And just to add another, equivalent alternative: println!("{:?}", roman2number.get(r0.as_str()));, the new-ish ::as_str method. – c0g Sep 14 '16 at 20:40
3

The definition of the get method looks as follows

fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V> where K: Borrow<Q>, Q: Hash + Eq

The first part is the type of object which you pass: Q. There are constraints on Q. The conditions on Q are that

  1. the key-type K needs to implement the Borrow trait over Q
  2. Q needs to implement the Hash and Eq traits.

Replacing this with your actual types means that the key-type &'static str needs to implement Borrow<String>. By the definition of Borrow, this means that a &'static str needs to be convertible to &String. But all the docs/texts I've read state that everywhere you'd use &String you should be using &str instead. So it makes little sense to offer a &str -> &String conversion, even if it would make life a little easier sometimes.

Since every reference type is borrowable as a shorter lived reference type.), you can pass a &str when a &'static str is the key-type, because &'static str implements Borrow<str>

  • Thank you. The explanation on Borrow makes sense! – skanur May 30 '16 at 11:29

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.