我正在尝试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`.
有人能解释一下为什么会发生这种情况吗?
HashMap::<&str, i32>::get::<str>(&map, &hello)
。 - JUSEOK KO