Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 874
Akin Aguda Avatar asked Nov 24 '25 04:11

Akin Aguda


1 Answers

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.
like image 144
phimuemue Avatar answered Nov 26 '25 17:11

phimuemue