2013-07-28 25 views
5

我無法弄清楚如何使用類型爲~str的密鑰的HashMap。例如,生鏽的字符串鍵控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"); 

基於this bug報告,我想

map.contains_key_equiv("hello"); 

,但得到

error: mismatched types: expected `&<V367>` but found `&'static str` (expected &-ptr but found &'static str) 

我真的不明白這最後的消息;有沒有人有建議?

回答

3

的聲明contains_key_equiv是:

pub fn contains_key_equiv<Q:Hash + Equiv<K>>(&self, key: &Q) -> bool 

也就是說,它需要一個參考的東西是Equiv alent到K == ~str。因此,要檢查&str(這是Equiv~str),我們需要一個& &str(對字符串片段的引用)。

map.contains_key_equiv(&("hello")); 

// or 

map.contains_key_equiv(& &"hello"); 

(請注意,這些都是等價的,只是需要得到迴避的事實,"foo" == &"foo"都是&str秒)

3

您有HashMap<K, V>~str(擁有的字符串)爲K;因此,它想要&Kthings,即&~str —對所擁有的字符串的引用。但是,您正在將它傳遞給一個靜態字符串(不帶任何印記的字符串文字[&,~等],"hello",類型爲&'static str)。

對於字符串文字,請勿使用.to_str();而應以~作爲前綴~"hello"。像那樣的字符串文字是~str。對於非文字,您通常應該使用&str.to_owned()

最終的代碼可以這樣操作:

use std::hashmap::HashMap; 

fn main() { 
    let mut h = HashMap::new::<~str, int>(); 
    h.insert(~"foo", 42); 
    printfln!("%?", h.find(&~"foo")); // => Some(&42) 
    printfln!("%?", h.contains_key(&~"foo")); // => true 

    // You don’t actually need the HashMap to own the keys (but 
    // unless all keys are 'static, this will be likely to lead 
    // to problems, so I don’t suggest you do it in reality) 
    let mut h = HashMap::new::<&str, int>(); 
    h.insert("foo", 42); 
    printfln!("%?", h.find(& &"foo")); // => Some(&42) 
} 

觀察到,當你需要的參考的參考,你不能這樣做&&因爲這是AND運算符;你需要做&(&x)& &x

(還請注意,從三個月前的任何問題可能不是最新的。我不能肯定的HashMap中的比較技術的當前狀態—試圖左右逢源,用正確的類型)