在闭包和迭代中移动结构实例
Move of struct instance in closure and in iteration
我最近开始使用简单的结构练习来学习 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
闭包中使用结构引用,因为它应该只改变迭代器实例?
- 是否可以在不 cloning/copying 和更改 API 的情况下解决上述 2 个问题?
在此先感谢您对理解此行为的任何帮助以及您对如何解决它的建议。
正如 Silvio 在评论中所建议的那样,问题出在借用对象的 contains
方法中。更改使用引用的方法使其全部工作。
我最近开始使用简单的结构练习来学习 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
闭包中使用结构引用,因为它应该只改变迭代器实例? - 是否可以在不 cloning/copying 和更改 API 的情况下解决上述 2 个问题?
在此先感谢您对理解此行为的任何帮助以及您对如何解决它的建议。
正如 Silvio 在评论中所建议的那样,问题出在借用对象的 contains
方法中。更改使用引用的方法使其全部工作。