首页 > 解决方案 > 在闭包和迭代中移动结构实例

问题描述

我最近开始使用带有结构的简单练习来学习 rust。在这种特殊情况下,我想遍历结构中的集合字段。但是我不断收到编译错误,因为对结构的引用不能在filter方法和循环中使用:

#[derive(Debug, PartialEq)]
pub struct CustomSet<T> {
    buckets: Vec<LinkedList<T>>,
    size: usize,
}

impl<T> CustomSet<T> where T: Eq + Clone + Hashable {
  pub fn new(input: &[T]) -> Self -> {...} // implemented
  pub fn contains(self, element: &T) -> bool {...} //implemented
  pub fn add(&mut self, element: T) {...} // implemented
  pub fn is_subset(&self, other: &Self) -> bool {
    for bucket in &self.buckets {
      for el in bucket {
        // error: cannot move out of `*other` which is behind a shared reference
        if !other.contains(&el) {
          return false;
        }
      }
    }
    return true;
  }
  pub fn intersection(&self, other: &Self) -> Self {
    let mut result = CustomSet::new(&[]);
    self.buckets.iter().for_each(|bucket|
      bucket.iter()
        // Cannot move out of `*other`, as `other` is a captured variable in an `FnMut` closure
        .filter(|el| other.contains(el))
        .for_each(|el| result.add(el.clone()))
      );
    result
  }
}

我想我的两个误解是:

在此先感谢您在理解此行为方面提供的任何帮助以及如何解决此问题的建议。

标签: rustborrow-checker

解决方案


正如 Silvio 在评论中所建议的那样,问题contains在于借用对象的方法。更改使用参考的方法使其一切正常。


推荐阅读