Reputation: 1986
I recently started to learn rust using simple exercises with structs. In this particular case I would like to iterate over a collection field in a struct. However I keep getting compilation errors because reference to a struct cannot be used in a filter
method as well as in a loop:
#[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
}
}
I guess my two misunderstandings are:
for
loop?filter
closure since it is supposed to be mutating only the iterator instance?Thanks in advance for any help in understanding this behavior and your suggestions how to fix it.
Upvotes: 0
Views: 132
Reputation: 1986
As suggested by Silvio in the comment the issue is in contains
method that borrows the object. Changing the method to use the reference made it all work.
Upvotes: 0