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>`
Share
Improve this question
edited Jan 18 at 0:30
cafce25
27.6k5 gold badges45 silver badges58 bronze badges
asked Jan 17 at 20:58
kecakisakecakisa
411 silver badge4 bronze badges
1
|
1 Answer
Reset to default 3You 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_iter
instead ofiter
as it returns the original value, not a borrowed one. In this case it would be&str
and not&&str
, which can be coerced from&String
– Timsib Adnap Commented Jan 18 at 11:29