2014-11-16 2 views
0

이 코드의 잘못된 점은 무엇입니까?녹이있는 구조체의 impl

use std::collections::{HashSet,HashMap}; 
struct Mod_allfun<'r> { 
    s: HashMap<&'r str, HashSet<&'r str>> 
} 
impl <'r>Mod_allfun<'r>{ 
    fn new() -> HashMap<&'r str,HashSet<&'r str>> {HashMap::new()} 
    fn insert(&mut self, c: &'r str, a:&'r [&'r str]){ 
     let aa: HashSet<&'r str>=a.iter().map(|&x| x).collect() ; 
     self.s.insert(c , aa ); 
    } 
} 
fn main() { 
    let z=Mod_allfun::new(); 
    z.insert("str1", ["str2","str3"]); 
} 

예상대로 작동하지 않는 이유는 알 수 없습니다. 이 예를 들어 수행 업무 :

use std::collections::{HashSet,HashMap}; 
fn main() { 
    let mut mod_allfun: HashMap<& str,HashSet<& str>>= HashMap::new(); 
    let c="str1"; 
    let a=["str2","str3"]; 
    let b = ||{ 
     mod_allfun.insert(c, a.iter().map(|&x| x).collect()); 
    }; 
} 
+1

최소한 오류 메시지가 나타납니다. –

답변

3

당신은 새로운 아닌 Mod_allfun에서의 HashMap를 반환하고 있습니다. 이것은 컴파일됩니다 :

use std::collections::{HashSet,HashMap}; 

struct ModAllfun<'r> { 
    s: HashMap<&'r str, HashSet<&'r str>> 
} 

impl<'r> ModAllfun<'r>{ 
    // return a ModAllfun, not a HashMap 
    fn new() -> ModAllfun<'r> { 
     ModAllfun { s: HashMap::new() } 
    } 

    fn insert(&mut self, c: &'r str, a:&'r [&'r str]){ 
     let aa: HashSet<&'r str> = a.iter().map(|&x| x).collect() ; 
     self.s.insert(c , aa); 
    } 
} 
fn main() { 
    let mut z = ModAllfun::new(); 
    // pull the array out into a variable to extend its lifetime 
    let arrs = ["str2","str3"]; 
    z.insert("str1", arrs); 
}