Skip to content

Instantly share code, notes, and snippets.

@asaaki
Forked from anonymous/playground.rs
Created January 26, 2018 08:42
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 asaaki/0f60723e0d0c51c33aaba2f293fd76b1 to your computer and use it in GitHub Desktop.
Save asaaki/0f60723e0d0c51c33aaba2f293fd76b1 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