Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=7ccac7cdf77cbc63a7d6fabd75a8b86e
- struct Message;
- trait Filter {
- type Checking;
- fn check(&self, to_check: &Self::Checking) -> bool;
- }
- struct SomeFilter<T> {
- handler: fn(&T) -> bool,
- }
- impl<T> Filter for SomeFilter<T> {
- type Checking = T;
- fn check(&self, to_check: &Self::Checking) -> bool {
- (self.handler)(to_check)
- }
- }
- struct Handler<T> {
- filters: Vec<Box<dyn Filter<Checking = T>>>,
- handler: fn(&T) -> bool,
- }
- impl<T> Handler<T> {
- fn run(&self, message: &T) -> Option<bool> {
- for filter in &self.filters {
- let _result = filter.check(message);
- if !_result {
- return None;
- }
- }
- Some((self.handler)(message))
- }
- }
- fn main() {
- let filter_always_true = Box::new(SomeFilter {
- handler: |_msg: &Message| true,
- }) as Box<dyn Filter<Checking=Message>>;
- let filters = vec![filter_always_true];
- let msg_handler = Handler::<Message> {
- filters: filters,
- handler: |_msg: &Message| true,
- };
- println!("{}", msg_handler.run(&Message {}).unwrap());
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement