-
-
Save archer884/bb9c65e01c256943cbbbf897ec71add5 to your computer and use it in GitHub Desktop.
Static vs. dynamic dispatch
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
#[derive(Debug, Default)] | |
struct State { | |
count: usize, | |
value: usize, | |
} | |
impl State { | |
fn average(&self) -> usize { | |
match self.count { | |
0 => self.value, | |
n => self.value / n, | |
} | |
} | |
} | |
enum TaggedUnion { | |
A(usize), | |
B(State), | |
} | |
trait Increment { | |
fn update(&self, state: &mut State); | |
} | |
impl Increment for usize { | |
fn update(&self, state: &mut State) { | |
state.count += 1; | |
state.value += *self; | |
} | |
} | |
impl Increment for State { | |
fn update(&self, state: &mut State) { | |
state.count += self.count; | |
state.value += self.value; | |
} | |
} | |
impl State { | |
fn apply_static(&mut self, increment: TaggedUnion) { | |
use self::TaggedUnion::*; | |
match increment { | |
A(value) => { | |
self.count += 1; | |
self.value += value; | |
} | |
B(State { count, value }) => { | |
self.count += count; | |
self.value += value; | |
} | |
} | |
} | |
fn apply_dynamic(&mut self, increment: &Increment) { | |
increment.update(self); | |
} | |
} | |
fn main() { | |
let mut state = State::default(); | |
state.apply_static(TaggedUnion::A(5)); | |
state.apply_static(TaggedUnion::B(State { count: 3, value: 13 })); | |
println!("{}", state.average()); | |
let mut state = State::default(); | |
state.apply_dynamic(&5); | |
state.apply_dynamic(&State { count: 3, value: 13 }); | |
println!("{}", state.average()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment