-
-
Save asaaki/0f60723e0d0c51c33aaba2f293fd76b1 to your computer and use it in GitHub Desktop.
Rust code shared from the playground
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
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