如何解决在闭包和迭代中移动结构体实例
我最近开始通过简单的结构练习来学习 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
方法中。更改方法以使用引用使其一切正常。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。