Search code examples
rusthashmapfnv

How to iterate through FnvHashMap in Rust


I have two FnvHashMap which is declared like first: FnvHashMap<(i32, i32), Employee> second: FnvHashMap<(i32, i32), Employee> Where Employee is

pub struct Employee {
    pub emp_id: i32,
    pub lang_id: i32,
    pub dept_id: f64,
    pub description: String,
}

I need to iterate through 'first' FnvHashMap and see if there is a matching record(emp_id and lang_id) in 'second' FnvHashMap
I may not need to consider dept_id and description

Thanks in Advance.

New code after implementing nested loop

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

  let deleted = second
            .iter()
            .filter(|(a, _)| !new.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>>,
}

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

Solution

  • Simply make two nested for loops to iterate through both maps and then compare the values you need from the two iterations of the loops, for example

    for (_, employee1) in &first {
        for (_, employee2) in &second {
            if employee1.emp_id == employee2.emp_id && employee1.lang_id == employee2.lang_id {
                /* Code here to run if a matching value is found */
            }
        }
    }