Created
February 1, 2016 16:55
-
-
Save ihrwein/58f483a0894c93a539ae to your computer and use it in GitHub Desktop.
Rust Higher-rank lifetime example
This file contains hidden or 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
// D is some data shared among event handlers | |
pub trait EventHandler<D> { | |
fn handle_event(&mut self, &mut D); | |
} | |
pub struct EH; | |
impl<'a> EventHandler<Data<'a>> for EH { | |
fn handle_event(&mut self, data: &mut Data<'a>) { | |
println!("{}", data._d1); | |
} | |
} | |
pub trait Reactor { | |
fn handle_events(&mut self); | |
fn register_handler(&mut self, handler: Box<for<'a> EventHandler<Data<'a>>>); | |
} | |
pub struct ReactorImpl { | |
handler: Box<for<'a> EventHandler<Data<'a>>>, | |
d1: i32, | |
d2: i32, | |
} | |
pub struct Data<'a> { | |
_d1: &'a i32, | |
_d2: &'a i32 | |
} | |
impl Reactor for ReactorImpl { | |
fn handle_events(&mut self) { | |
let mut data = Data {_d1: &self.d1, _d2: &self.d2}; | |
self.handler.handle_event(&mut data); | |
} | |
fn register_handler(&mut self, handler: Box<for<'a> EventHandler<Data<'a>>>) { | |
self.handler = handler; | |
} | |
} | |
fn main() { | |
let mut reactor = ReactorImpl{handler: Box::new(EH), d1: 1, d2:2}; | |
reactor.handle_events(); | |
} |
This file contains hidden or 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
// D is some data shared among event handlers | |
pub trait EventHandler<D> { | |
fn handle_event(&mut self, &mut D); | |
} | |
pub trait Reactor { | |
fn handle_events(&mut self); | |
fn register_handler(&mut self, handler: Box<for<'a> EventHandler<(&'a i32, &'a i32)>>); | |
} | |
pub struct ReactorImpl { | |
handler: Box<for<'a> EventHandler<(&'a i32, &'a i32)>>, | |
d1: i32, | |
d2: i32, | |
} | |
pub struct Data<'a> { | |
d1: &'a i32, | |
d2: &'a i32 | |
} | |
impl Reactor for ReactorImpl { | |
fn handle_events(&mut self) { | |
let mut data = Data {d1: &self.d1, d2: &self.d2}; | |
let mut a = (&self.d1, &self.d2); | |
self.handler.handle_event(&mut a); | |
} | |
fn register_handler(&mut self, handler: Box<for<'a> EventHandler<(&'a i32, &'a i32)>>) { | |
self.handler = handler; | |
} | |
} | |
fn main() { | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment