-2

I would like to implement a struct as below. The struct instance, its fields and all the elements inside should be immutable and have the same lifetime. But I got stuck by the lifetime thing.

pub struct Foo {
    keys: Vec<String>,
    vals: Vec<i32>,
    mapping: HashMap<&str, &i32>,
}

And try to create a instance like this:

pub fn new(keys: &Vec<&str>, vals: &Vec<i32>) -> Foo {
    let result = Foo {
        keys: keys.iter().map(|x| x.to_string()).collect(),
        vals: vals.clone(),
        mapping: HashMap::new(),
    };
    let n = keys.len();
    for i in 0..n {
        result.mapping.insert(&result.keys[i], &result.vals[i]);
    }
    return result;
}
tushushu
  • 17
  • 4

0 Answers0