2013-07-28 22 views
5

HashMap'in nasıl kullanılacağını bulmakta zorlandığım bir deyim ile ~str türünde anahtar. Örneğin, this hata raporuna göreDize anahtarlı HashMap pas içinde mi?

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"); 

, ben

map.contains_key_equiv("hello"); 

çalıştı ama

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

Gerçekten bu son mesajı anlamıyorum var; kimsenin bir öneri var mı?

cevap

3

beyanı contains_key_equiv geçerli:

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

, bu K == ~str için alent Equiv bir şey bir başvuru alır. Bu nedenle &str (için Equiv alent) olup olmadığını kontrol etmek için & &str (bir dize dilimine başvuru) istiyoruz.

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

// or 

map.contains_key_equiv(& &"hello"); 

(bunlar eşdeğerdir ve sadece "foo" == &"foo" hem &str ler olduğu gerçeği aşmanın gerekli olduğunu unutmayın.)

3

HashMap<K, V>~str (sahip olunan bir dize) K; bu nedenle, things için &K'un bulunduğu yer, yani sahip olunan bir dizgeye bir referans olan &~str —. Bununla birlikte, onu statik bir dizgeye (herhangi bir işaretsiz [&, ~, vb.], "hello" türünde, &'static str türünde bir dizgiden oluşan bir başvuru) iletiyorsunuz.

Dize değişmezleri için .to_str(); bunun yerine, ~ ile ~"hello" olarak önekleyin. Bunun gibi bir dizgi, ~str türündedir. Gayri resmi olmayanlar için, genellikle &str'un .to_owned()'unu kullanmalısınız.

nihai kodu şöyle çalışabilir:

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) 
} 

Bir referansa Referans gerektiğinde bu boole VE operatörü olduğu gibi && yapamaz gözlemleyin; &(&x) veya & &x yapmalısınız.

(Not ayrıca üç ay önce herhangi bir sorun cari olmayabilir;. Doğru türleriyle, her iki yönde deneyin — hashmap en karşılaştırma teknikleri mevcut durumu belli değilim)