Advertisement
NLinker

Vector of polymorphic boxes with dyn trait

Apr 21st, 2020
1,396
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.21 KB | None | 0 0
  1. // https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=7ccac7cdf77cbc63a7d6fabd75a8b86e
  2.  
  3. struct Message;
  4.  
  5. trait Filter {
  6.     type Checking;
  7.     fn check(&self, to_check: &Self::Checking) -> bool;
  8. }
  9.  
  10. struct SomeFilter<T> {
  11.     handler: fn(&T) -> bool,
  12. }
  13.  
  14. impl<T> Filter for SomeFilter<T> {
  15.     type Checking = T;
  16.     fn check(&self, to_check: &Self::Checking) -> bool {
  17.         (self.handler)(to_check)
  18.     }
  19. }
  20.  
  21. struct Handler<T> {
  22.     filters: Vec<Box<dyn Filter<Checking = T>>>,
  23.     handler: fn(&T) -> bool,
  24. }
  25.  
  26. impl<T> Handler<T> {
  27.     fn run(&self, message: &T) -> Option<bool> {
  28.         for filter in &self.filters {
  29.             let _result = filter.check(message);
  30.             if !_result {
  31.                 return None;
  32.             }
  33.         }
  34.  
  35.         Some((self.handler)(message))
  36.     }
  37. }
  38.  
  39. fn main() {
  40.     let filter_always_true = Box::new(SomeFilter {
  41.         handler: |_msg: &Message| true,
  42.     }) as Box<dyn Filter<Checking=Message>>;
  43.    
  44.     let filters = vec![filter_always_true];
  45.     let msg_handler = Handler::<Message> {
  46.         filters: filters,
  47.         handler: |_msg: &Message| true,
  48.     };
  49.  
  50.     println!("{}", msg_handler.run(&Message {}).unwrap());
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement