Mapping a HashMap lookup over Index from Enumeration of a String in Rust

Viewed 23

I would like to look up some strings in a HashMap by first iterating through a string, enumerating the index of the character, and using that position as my lookup for the Key in the HashMap

This is what I am trying:

use std::collections::HashMap;

fn main()
{
    let weight = HashMap::from([
         ("1", 8),
         ("2", 7),
         ("3", 6),
         ("4", 5),
         ("5", 4),
         ("6", 3),
         ("7", 2),
         ("8", 1),
         ("9", 0),
         ("10", 9),
         ("11", 8),
         ("12", 7),
         ("13", 6),
         ("14", 5),
         ("15", 4),
         ("16", 3),
         ("17", 2)
    ]);

    let s = String::from("Hello World");

    let weights: Vec<_> = s.chars()
                           .enumerate()
                           .map(|(i, c)| weight.get( &(i+1).to_string() ).unwrap_or(&0))
                           .collect();
    dbg!(weights);
}

But am getting confused with the errors regarding how to perform the map properly. I understand that .chars().enumerate() creates an iterator of pairs (idx, char) on the string, but I want to use the idx, add 1 to it, then use that value as the key lookup in my HashMap. Where am I going wrong?

Error I am receiving: the trait Borrow<String> is not implemented for &str.

However, I thought by casting to String via .to_string() I could perform this?

error[E0277]: the trait bound `&str: Borrow<String>` is not satisfied
  --> src\main.rs:76:56
   |
76 | ...                   .map(|(i, c)| weight.get( &(i+1).to_string() ).unwrap_or(&0))
   |                                            ---  ^^^^^^^^^^^^^^^^^^ the trait `Borrow<String>` is not implemented for `&str`
   |                                            |
   |                                            required by a bound introduced by this call
0 Answers
Related