v217
v217

Reputation: 805

impl for structs in rust

What's wrong with this code?

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

I have no idea why this does not work as expected! This for example does work:

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

Upvotes: 0

Views: 1305

Answers (1)

James Moughan
James Moughan

Reputation: 413

You're returning a HashMap from new, not a Mod_allfun. This does compile:

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

Upvotes: 3

Related Questions