How to resolve compilation error while borrowing values in Rust

101 Views Asked by At

I am new to Rust and here is my code to iterate through two FnvHashMaps and find the difference

impl SaveChanges for Employee{
    type Item = Employee;
    type List = FnvHashMap<(i32, i32), Employee>;
    type Id = (i32, i32);

    fn find_changes(
        old: &FnvHashMap<(i32, i32), Employee>,
        new: FnvHashMap<(i32, i32), Employee>,
    ) -> Changes<Employee, (i32, i32)> {
  let deleted = second
            .iter()
            .filter(|(a, _)| !new.contains_key(a))
            .map(|(&a, _)| a)
            .collect();

for (_, employee1) in &first {
    for (_, employee2) in &second {
        if employee1.emp_id == employee2.emp_id && employee1.lang_id == employee2.lang_id {
            
                    values.push(OldNew {
                        old: employee2,
                        new: employee1,
                    });
        }
    }
}
     let new = first
            .into_iter()
            .filter(|(a, _)| !old.contains_key(a))
            .map(|(_, a)| a)
            .collect();


 
 Changes {
            deleted,
            new,
            values,
        }
}

pub struct Changes<T, I> {
    pub deleted: Vec<I>,
    pub new: Vec<T>,
    pub values: Vec<OldNew<T>>,
}

Rust throwing compilation error when I add those values to another vector

values,
expected struct `organization::models::employee_stat::Employee`, found `&organization::models::employee_stat::Employee`

Any help would be really appreciated. Thanks

1

There are 1 best solutions below

4
user4815162342 On

The problem is that your deleted variable contains Vec<&T>, not the Vec<T> expected by the deleted field. This is because it is obtained from second.iter() which iterates over references to keys and values in the hash table. There is a similar issue with values.

To fix this, you should either use into_iter() when iterating over the hashmaps, or call clone() to convert &T to T.