【发布时间】:2016-09-28 00:15:27
【问题描述】:
我试图了解 HashMaps 在 Rust 中是如何工作的,我想出了这个例子。
use std::collections::HashMap;
fn main() {
let mut roman2number: HashMap<&'static str, i32> = HashMap::new();
roman2number.insert("X", 10);
roman2number.insert("I", 1);
let roman_num = "XXI".to_string();
let r0 = roman_num.chars().take(1).collect::<String>();
let r1: &str = &r0.to_string();
println!("{:?}", roman2number.get(r1)); // This works
// println!("{:?}", roman2number.get(&r0.to_string())); // This doesn't
}
当我尝试编译未注释最后一行的代码时,我收到以下错误
error: the trait bound `&str: std::borrow::Borrow<std::string::String>` is not satisfied [E0277]
println!("{:?}", roman2number.get(&r0.to_string()));
^~~
note: in this expansion of format_args!
note: in this expansion of print! (defined in <std macros>)
note: in this expansion of println! (defined in <std macros>)
help: run `rustc --explain E0277` to see a detailed explanation
docs 的 Trait 实现部分将取消引用指定为 fn deref(&self) -> &str
那么这里发生了什么?
【问题讨论】:
-
我认为在这里使用
Borrow特征是错误的(无论是谁编写了HashMap::get)。基本上,通用绑定说:您可以将对任何类型的引用传递给get,如果键类型可作为该类型借用。实际上应该是:您可以将任何类型传递给get,只要该类型可强制转换为键类型即可。但是我们不能向后兼容地解决这个问题:(
标签: hashmap rust dereference borrowing