Skip to content

Instantly share code, notes, and snippets.

Created December 11, 2017 14:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/3eac7214967e1892b48a50c773b1c814 to your computer and use it in GitHub Desktop.
Save anonymous/3eac7214967e1892b48a50c773b1c814 to your computer and use it in GitHub Desktop.
Rust code shared from the playground
use std::ops::Deref;
struct StateFn(fn(&mut Machine) -> StateFn);
impl Deref for StateFn {
type Target = fn(&mut Machine) -> StateFn;
fn deref(&self) -> &Self::Target {
&self.0
}
}
struct Machine {
decision: bool
}
impl Machine {
fn start(&mut self) -> StateFn {
if self.decision {
StateFn(Self::state2)
} else {
StateFn(Self::state3)
}
}
fn state2(&mut self) -> StateFn {
println!("fooo");
StateFn(Self::state2)
}
fn state3(&mut self) -> StateFn {
println!("bar");
StateFn(Self::state2)
}
}
fn main() {
let mut m = Machine { decision: true };
let mut current = StateFn(Machine::start);
for _ in 0..3 {
current = current(&mut m);
}
println!("------");
let mut m = Machine { decision: false };
let mut current = StateFn(Machine::start);
for _ in 0..3 {
current = current(&mut m);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment