Skip to content

Instantly share code, notes, and snippets.

@bwindels
Last active November 22, 2017 18:01
Show Gist options
  • Save bwindels/98f6ac08fb2dcc97924e37b9eace91e7 to your computer and use it in GitHub Desktop.
Save bwindels/98f6ac08fb2dcc97924e37b9eace91e7 to your computer and use it in GitHub Desktop.
use std::cell::{RefCell, RefMut, BorrowMutError};
enum Event {
Click,
Close,
Keystroke
}
trait Child<'a> {
fn handle_event(&'a mut self, event: Event, ctx: &'a RefCell<u64>) -> u64;
}
struct FooChild<'a> {
value: Option<RefMut<'a, u64>>
}
impl<'a> Child<'a> for FooChild<'a> {
fn handle_event(&'a mut self, event: Event, ctx: &'a RefCell<u64>) -> u64 {
match event {
Event::Click => {
self.value = Some(ctx.try_borrow_mut().unwrap());
0
},
Event::Keystroke => {
if let Some(ref mut value) = self.value {
**value = (**value) + 2;
(**value) * (**value)
}
else {
0
}
},
Event::Close => {
self.value = None;
1
},
_ => 0
}
}
}
struct Main<C> {
child: C,
store: RefCell<u64>
}
impl<'a, C: Child<'a>> Main<C> {
pub fn handle_event(&mut self, event: Event) -> u64 {
self.child.handle_event(event, &self.store)
}
}
fn main() {
let m = Main {
child: FooChild {value: None},
store: RefCell::new(0)
};
println!("Click: {}", m.handle_event(Event::Click));
println!("Keystroke: {}", m.handle_event(Event::Keystroke));
println!("Keystroke: {}", m.handle_event(Event::Keystroke));
println!("Close: {}", m.handle_event(Event::Close));
}
@bwindels
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment