I have a program that involves examining a complex data structure to see if it has any defects. (It\'s quite complicated, so I\'m posting example code.) All of the checks ar
I eventually found a way to do it that I'm happy with. Instead of having a vector of Box
objects, have a vector of closures that all have the same type, abstracting away the very functions that get called:
fn main() {
type Probe = Box Option>>;
let numbers: Vec = vec![ 1, -4, 64, -25 ];
let checks = vec![
Box::new(|num| EvenCheck.check_number(num).map(|u| Box::new(u) as Box)) as Probe,
Box::new(|num| NegativeCheck.check_number(num).map(|u| Box::new(u) as Box)) as Probe,
];
for number in numbers {
for check in checks.iter() {
if let Some(error) = check(number) {
println!("{}", error.description());
}
}
}
}
Not only does this allow for a vector of Box
objects to be returned, it allows the Check
objects to provide their own Error associated type which doesn't need to implement PartialEq
. The multiple as
es look a little messy, but on the whole it's not that bad.