Created
December 11, 2017 14:05
-
-
Save anonymous/3eac7214967e1892b48a50c773b1c814 to your computer and use it in GitHub Desktop.
Rust code shared from the playground
This file contains hidden or 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
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