How can I have a collection of objects that differ by their associated type?

后端 未结 3 601
小蘑菇
小蘑菇 2020-11-30 15:10

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

3条回答
  •  失恋的感觉
    2020-11-30 15:43

    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 ases look a little messy, but on the whole it's not that bad.

提交回复
热议问题