我正在尝试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`.有人能解释一下为什么会这样吗?
发布于 2021-01-03 12:55:03
.get查找&Q作为参数,其中键类型K为Borrow<Q>。由于有一个将&T借用到&T中的总括实现,所以&str (键类型)可以借用到&str (参数类型)中
然而,在执行&hello时,您实际上有一个&String,这意味着Rust推断String为Q,因此它试图将&str借用到&String中,这显然是不可能的。所以,让显式关于deref强制,以便Rust知道它应该将&String删除到&str中。
let hello_score: Option<&i32> = map.get(&hello as &str);或,
let hello_score: Option<&i32> = map.get(&*hello);https://stackoverflow.com/questions/65549983
复制相似问题