最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

rust - the trait `Borrow<String>` is not implemented for `&&str` - Stack Overflow

programmeradmin8浏览0评论

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
  • You can use into_iter instead of iter 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
Add a comment  | 

1 Answer 1

Reset to default 3

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

发布评论

评论列表(0)

  1. 暂无评论