I want to call a custom defined filter in multiple struct methods, but it should somehow have access to a certain property of the struct.
Here is a basic example of what I have so far:
struct Collection {
elements: Vec<isize>,
scope: isize
}
impl Collection {
fn action1(&self) {
for e in (&self.elements).iter().filter(Collection::filter) {
println!("do something ...");
}
}
fn action2(&self) {
// filter and do something with the elements
}
fn action3(&self) {
// filter and do something with the elements
}
fn filter(cur: &&isize) -> bool {
// Determine if current element needs to be filtered based on the scope value
true
}
}
fn main() {
let c = Collection { elements: vec![1, 2, 3, 4, 5, 6, 7, 8], scope: 2 };
c.action1();
c.action2();
}
I'm aware that I could pass a closure / block directly as an argument, but that would imply copying the filter logic across multiple methods, which is what I want to avoid.
It would had been nice to be able to do the following:
fn filter(&self, cur: &&isize) -> bool {
}
However this won't compile, most likely because it's really a method, not a function.
Perhaps this is doable if the function returns a closure, but I just couldn't make the filter accept it as a response.
Having this said, how should I handle the data filtering?