I have a code that should combine an array with the names of commands with an array with functions.
use std::{collections::HashMap, env};
fn echo(){}
fn main() {
    let names = vec!["echo"];
    let funcs = vec![echo()];
    let commands: HashMap<&&str, &()> = names.iter().zip(funcs.iter()).collect();
    let args: Vec<String> = env::args().collect();
    let command = commands[&args[1]];
}
I try to compile it but it write:
   |
10 |     let command = commands[&args[1]];
   |                            ^^^^^^^^ the trait `Borrow<String>` is not implemented for `&&str`
   |
   = help: the trait `Borrow<str>` is implemented for `String`
   = note: required for `HashMap<&&str, &()>` to implement `Index<&String>`
    
                
I have a code that should combine an array with the names of commands with an array with functions.
use std::{collections::HashMap, env};
fn echo(){}
fn main() {
    let names = vec!["echo"];
    let funcs = vec![echo()];
    let commands: HashMap<&&str, &()> = names.iter().zip(funcs.iter()).collect();
    let args: Vec<String> = env::args().collect();
    let command = commands[&args[1]];
}
I try to compile it but it write:
   |
10 |     let command = commands[&args[1]];
   |                            ^^^^^^^^ the trait `Borrow<String>` is not implemented for `&&str`
   |
   = help: the trait `Borrow<str>` is implemented for `String`
   = note: required for `HashMap<&&str, &()>` to implement `Index<&String>`
    
        
            
                
                    
                    You can pretty easily just get an &&str from a String using the as_str method:
let command = commands[&args[1].as_str()];
But I would recommend against having a double-reference as your key type, and use just &str instead. The Iterator::copied method will dereference each &&str into a &str:
let commands: HashMap<&str, &()> = names.iter().copied().zip(funcs.iter()).collect();
let command = commands[args[1].as_str()];
playground

into_iterinstead ofiteras it returns the original value, not a borrowed one. In this case it would be&strand not&&str, which can be coerced from&String– Timsib Adnap Commented Jan 18 at 11:29