Created
May 8, 2020 03:53
-
-
Save aboglioli/59b0589becf2b8cd274b0d0cfe850c7c to your computer and use it in GitHub Desktop.
Dynamic dispatch with Box and trait objects. Function handler.
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
trait Handler { | |
fn handle(&self); | |
} | |
struct Data1 { | |
v: i32, | |
} | |
impl Handler for Data1 { | |
fn handle(&self) { | |
println!("Data1: {}", self.v); | |
} | |
} | |
struct Data2; | |
impl Handler for Data2 { | |
fn handle(&self) { | |
println!("Data2"); | |
} | |
} | |
struct Func<F: Fn()> { | |
f: F, | |
} | |
impl<F: Fn()> Func<F> { | |
fn new(f: F) -> Func<F> { | |
Func { | |
f, | |
} | |
} | |
} | |
impl<F: Fn()> Handler for Func<F> { | |
fn handle(&self) { | |
(self.f)() | |
} | |
} | |
fn proc(handlers: Vec<&dyn Handler>) { | |
for h in handlers { | |
h.handle(); | |
} | |
} | |
fn make(i: i32) -> Box<dyn Handler> { | |
if i < 10 { | |
Box::new(Data1{v: 32}) | |
} else if i < 15 { | |
Box::new(Func::new(|| println!("Func"))) | |
} | |
else { | |
Box::new(Data2) | |
} | |
} | |
fn main() { | |
let d1 = make(5); | |
let d2 = make(15); | |
let f = make(12); | |
proc(vec![&*d1, &*d2, &*f]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment