rust - 在闭包和迭代中移动结构实例
问题描述
我最近开始使用带有结构的简单练习来学习 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
}
}
我想我的两个误解是:
for
为什么在循环的情况下会发生结构实例的移动?- 为什么我不能在
filter
闭包中使用结构引用,因为它应该只改变迭代器实例? - 是否可以在不克隆/复制和更改 API 的情况下解决上述 2 个问题?
在此先感谢您在理解此行为方面提供的任何帮助以及如何解决此问题的建议。
解决方案
正如 Silvio 在评论中所建议的那样,问题contains
在于借用对象的方法。更改使用参考的方法使其一切正常。
推荐阅读
- azure - 如何通过 Graph API 从 MS Teams 中恢复通话记录信息
- angular - 如何使用从 HttpClient (Angular) 获得的数据进行排序创建 mat-table
- python - 为什么列表列表的 zip() 会输出这样的结果?
- angular - 如何使用 Prime NG 在条件下选择单选按钮
- amazon-web-services - AWS S3 - java.net.UnknownHostException:repo-user-bucket.s3.us-west-2.amazonaws.com
- ssh - gcp 上的远程执行配置程序未与主机连接
- xaml - 更新 Badge、Xamarin Forms 应用程序中的计数器
- json - Postgres Json_each_Text() 函数
- python - 带有元素的 Python 列表操作
- python - 为什么这个 python 代码的输出是 False?