Akin Aguda
Akin Aguda

Reputation: 463

the trait `std::borrow::Borrow<char>` is not implemented for `&str`

let mut map: HashMap<&str, u32> = HashMap::new();

for (i, c) in text.chars().enumerate() {
    if map.contains_key(&c) {
    // Do something
    }
}

the trait std::borrow::Borrow<char> is not implemented for &str

I need an explanation of this error and how to fix it please. I am looping through every character in a text and inserting the ones not already in a hashmap into the hash map. But i keep getting the error as stated above.

Upvotes: 3

Views: 1432

Answers (1)

phimuemue
phimuemue

Reputation: 35983

chars is an Iterator, whose Item = char, so your HashMap<&str, u32> is not compatible with it.

&str is a string slice (essentialy a sequence of characters), while a char is a single character.

You must decide:

  • Should map really map from &str to u32? Or possibly from char? Or possibly from &char?
  • If you go for &str, you must convert chars's elements to &str.

Upvotes: 3

Related Questions