2013-07-28 5 views
5

id0om 유형의 ~str 키가있는 HashMap을 사용하는 방법을 알아내는 데 문제가 있습니다. 예를 들어, this 버그 리포트를 바탕으로문자열 키 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"); 

, 나는

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 

, 그것은 K == ~str에가 흐르고 Equiv 무언가에 대한 참조를합니다. 따라서 &str (Equiv~str으로 지정)을 확인하려면 & &str (문자열 슬라이스에 대한 참조)이 필요합니다.

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

// or 

map.contains_key_equiv(& &"hello"); 

(이것들은 동일하고, 단지 "foo" == &"foo" 모두 &str의 사실 해결하기 위해 필요합니다.)

3

HashMap<K, V>~str (소유 문자열)은 K입니다. 따라서 원하는 위치, —에 대해서는 &K, 소유 한 문자열에 대한 참조는 things입니다. 그러나 정적 문자열 (&, ~ 등)이없는 문자열 리터럴 인 "hello"&'static str 유형의 정적 문자열에 대한 참조를 전달합니다.

문자열 리터럴의 경우 .to_str()을 사용하지 마십시오. 대신 ~이라는 접두어를 ~"hello"으로 붙이십시오. 그런 문자열 리터럴은 ~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을 수행해야합니다.

(참고도 3 개월 전에에서 어떤 문제가 현재하지 않을 수;. 나는 올바른 유형의 두 가지 방법을 시도 —의 HashMap의 비교 기술의 현재 상태 확실하지 않다)