Skip to content

Instantly share code, notes, and snippets.

@kyrylo
Created July 20, 2018 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kyrylo/b0a989d5e23aa6afcd4bb6c5587d215a to your computer and use it in GitHub Desktop.
Save kyrylo/b0a989d5e23aa6afcd4bb6c5587d215a to your computer and use it in GitHub Desktop.
Filters
fn main() {
let mut notifier = Notifier::new();
notifier.add_filter(|n| n.incr_count(1));
notifier.add_filter(|n| n.incr_count(1));
let mut notice = Notice::new();
println!("Before: {:#?}", notice);
notifier.notify(&mut notice);
println!("After: {:#?}", notice);
}
#[derive(Debug)]
struct Notice {
count: i32,
}
impl Notice {
pub fn new() -> Self {
Self {
count: 0,
}
}
pub fn incr_count(&mut self, count: i32) {
self.count += count;
}
}
struct Notifier<'a> {
filters: Vec<Box<Fn(&mut Notice) + 'a>>
}
impl<'a> Notifier<'a> {
pub fn new() -> Self {
Self {
filters: Vec::new(),
}
}
pub fn add_filter<T: Fn(&mut Notice) + 'a>(&mut self, filter: T) {
self.filters.push(Box::new(filter));
}
pub fn notify(&self, notice: &mut Notice) {
for filter in &self.filters {
filter(notice);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment