Last active
November 22, 2017 18:01
-
-
Save bwindels/98f6ac08fb2dcc97924e37b9eace91e7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fixed version: https://play.rust-lang.org/?gist=3be53b681c3960cdbda75238170d6183&version=stable