生锈的结构

时间:2014-11-16 16:07:49

标签: arrays rust lifetime

这段代码出了什么问题?

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 个答案:

答案 0 :(得分: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);
}