我无法弄清楚如何使用具有~str惯用类型的键的HashMap .例如,
let mut map: hashmap::HashMap<~str, int> = hashmap::HashMap::new();
// Inserting is fine, I just have to copy the string.
map.insert("hello".to_str(), 1);
// If I look something up, do I really need to copy the string?
// This works:
map.contains_key(&"hello".to_str());
// This doesn't: as expected, I get
// error: mismatched types: expected `&~str` but found `&'static str` (expected &-ptr but found &'static str)
map.contains_key("hello");
Run Code Online (Sandbox Code Playgroud)
根据这个错误报告,我试过了
map.contains_key_equiv("hello");
Run Code Online (Sandbox Code Playgroud)
但得到了
error: mismatched types: expected `&<V367>` but found `&'static str` (expected &-ptr but found &'static str)
Run Code Online (Sandbox Code Playgroud)
我真的不明白这最后的消息; 有没有人有建议?
的声明contains_key_equiv是:
pub fn contains_key_equiv<Q:Hash + Equiv<K>>(&self, key: &Q) -> bool
Run Code Online (Sandbox Code Playgroud)
也就是说,它引用了感兴趣的Equiv事物K == ~str。因此,为了检查 a &str(与 相关Equiv)~str,我们需要 a & &str(对字符串切片的引用)。
map.contains_key_equiv(&("hello"));
// or
map.contains_key_equiv(& &"hello");
Run Code Online (Sandbox Code Playgroud)
(请注意,这些是等效的,只是为了绕过"foo" == &"foo"两者都是&strs 的事实。)
| 归档时间: |
|
| 查看次数: |
4738 次 |
| 最近记录: |