首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >没有为‘&str`’实现特性`Borrow<String>。

没有为‘&str`’实现特性`Borrow<String>。
EN

Stack Overflow用户
提问于 2021-01-03 12:43:39
回答 1查看 5.5K关注 0票数 18

我正在尝试The Rust Programming Language书中的一些示例,并有以下代码片段:

代码语言:javascript
复制
fn main() {
    let mut map: HashMap<&str, i32, RandomState> = HashMap::new();
    let hello: String = String::from("hello");
    map.insert(&hello, 100);
    println!("{:?}", map); //{"hello": 100}
    let first_hello_score: Option<&i32> = map.get("hello"); // This compiles
    let hello_score: Option<&i32> = map.get(&hello); // This does not compile
}

在运行cargo check时,我看到:

代码语言:javascript
复制
error[E0277]: the trait bound `&str: Borrow<String>` is not satisfied
  --> src/main.rs:26:27
   |
26 |     let hello_score = map.get(&hello);
   |                           ^^^ the trait `Borrow<String>` is not implemented for `&str`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0277`.

有人能解释一下为什么会这样吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-03 12:55:03

.get查找&Q作为参数,其中键类型KBorrow<Q>。由于有一个将&T借用到&T中的总括实现,所以&str (键类型)可以借用到&str (参数类型)中

然而,在执行&hello时,您实际上有一个&String,这意味着Rust推断StringQ,因此它试图将&str借用到&String中,这显然是不可能的。所以,让显式关于deref强制,以便Rust知道它应该将&String删除到&str中。

代码语言:javascript
复制
let hello_score: Option<&i32> = map.get(&hello as &str);

或,

代码语言:javascript
复制
let hello_score: Option<&i32> = map.get(&*hello);
票数 30
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65549983

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档