特性 `Borrow<String> 没有为 `&str` 实现

时间:2021-01-03 12:43:39

标签: rust

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

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 时,我看到:

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`.

有人可以解释为什么会发生这种情况吗?

1 个答案:

答案 0 :(得分:5)

.get 寻找 &Q 作为参数,其中键类型 KBorrow<Q>。由于有一个整体实现将 &T 借入 &T&str(键类型)可以借入 &str(参数类型)

然而,在执行 &hello 时,您实际上有一个 &String,这意味着 Rust 推断 StringQ,因此它试图借用 &str进入&String,这显然是不可能的。因此,对解引用强制明确,以便 Rust 知道它应该将 &String 解引用为 &str

let hello_score: Option<&i32> = map.get(&hello as &str);

或者,

let hello_score: Option<&i32> = map.get(&*hello);