如何在Rust中借用值时解决编译错误 [英] How to resolve compilation error while borrowing values in Rust

查看:67
本文介绍了如何在Rust中借用值时解决编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Rust的新手,这是我的代码来遍历两个FnvHashMaps并找出不同之处

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

推荐答案

问题是您的已删除变量包含 Vec<& T> ,而不是 deleted 字段所期望的> Vec< T> .这是因为它是从 second.iter()获得的,该代码遍历引用到哈希表中的键和值. values 也有类似的问题.

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.

要解决此问题,您应在遍历哈希表时使用 into_iter(),或调用 clone()转换& T 转换为 T .

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

这篇关于如何在Rust中借用值时解决编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆