Skip to content

Instantly share code, notes, and snippets.

@archer884
Created April 3, 2018 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save archer884/bb9c65e01c256943cbbbf897ec71add5 to your computer and use it in GitHub Desktop.
Save archer884/bb9c65e01c256943cbbbf897ec71add5 to your computer and use it in GitHub Desktop.
Static vs. dynamic dispatch
#[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