Last active
May 9, 2020 21:04
-
-
Save aboglioli/e992a2ff49987931419bf7099ed2a10c to your computer and use it in GitHub Desktop.
Generic to trait object and boxing (Box<T>) inside method.
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::fmt::Debug; | |
trait Handler: Drop + Debug { | |
fn handle(&self, data: &Data); | |
} | |
#[derive(Debug)] | |
struct Processor(String); | |
impl Handler for Processor { | |
fn handle(&self, data: &Data) { | |
println!("- handling: {:?}", data); | |
} | |
} | |
impl Drop for Processor { | |
fn drop(&mut self) { | |
println!("- dropping: {}", self.0); | |
} | |
} | |
#[derive(Debug)] | |
struct Data { | |
handler: Box<dyn Handler>, | |
} | |
impl Data { | |
fn new<'a, H>(handler: H) -> Self | |
where | |
H: Handler + 'static, | |
{ | |
Data { handler: Box::new(handler) } | |
} | |
fn set_handler<H: 'static + Handler>(&mut self, handler: H) { | |
self.handler = Box::new(handler); | |
} | |
fn exec(&self) { | |
self.handler.handle(self); | |
} | |
} | |
fn main() { | |
let p1 = Processor("Processor 1".to_string()); | |
println!("Using {:?}", p1); | |
let mut d = Data::new(p1); | |
d.exec(); | |
{ | |
let p2 = Processor("Processor 2".to_string()); | |
println!("Using {:?}", p2); | |
d.set_handler(p2); // thanks to 'static | |
} | |
d.exec(); | |
let p3 = Processor("Processor 3".to_string()); | |
println!("Using {:?}", p3); | |
d.set_handler(p3); | |
d.exec(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment