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

我正在尝试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`.

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

回答

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

但是,这样做的时候&hello,你确实有一个&String,这意味着锈推断StringQ,所以它会试图借&str&String,这显然是不可能的。因此,明确deref 强制,以便 Rust 知道它应该 deref &Stringinto &str

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

或者,

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


以上是特性`Borrow&lt;String&gt;没有为`&amp;str`实现的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>