Created
July 5, 2017 22:39
-
-
Save kyleheadley/f4073eef29d56ef67e6b1a489c3a7d47 to your computer and use it in GitHub Desktop.
FSM example in rust
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
#![allow(unused)] | |
use std::fmt::Debug; | |
#[derive(Debug)] | |
struct Door<S: DoorState> { | |
state: S, | |
} | |
trait DoorState {} | |
struct Open; impl DoorState for Open {} | |
#[derive(Debug)] | |
struct Closed; impl DoorState for Closed {} | |
struct Jammed; impl DoorState for Jammed {} | |
enum OpenResult { | |
Open(Door<Open>), | |
Jammed(Door<Jammed>), | |
} | |
impl<S: DoorState+Debug> Door<S> { | |
fn what(&self) { | |
println!("{:?}",self); | |
} | |
} | |
impl Door<Open> { | |
fn close(self) -> Door<Closed> { | |
Door{state: Closed} | |
} | |
} | |
impl Door<Closed> { | |
fn new() -> Door<Closed> { | |
Door{state: Closed} | |
} | |
fn open(self) -> OpenResult { | |
OpenResult::Open(Door{state:Open}) | |
} | |
} | |
impl OpenResult { | |
fn ok(self, m: &str) -> Door<Open> { | |
match self { | |
OpenResult::Open(d) => d, | |
OpenResult::Jammed(_) => panic!(m.to_string()), | |
} | |
} | |
} | |
struct Unknown; | |
fn main() { | |
let d = Door::new(); | |
let o = match d.open() { | |
OpenResult::Open(d) => d, | |
OpenResult::Jammed(d) => { | |
println!("Jammed!"); | |
return | |
} | |
}; | |
let c = o.close(); | |
let f = c | |
.open().ok("jammed!") | |
.close() | |
//.close() // compile error, wrong type | |
.open().ok("jammed?") | |
.close() | |
; | |
f.what(); | |
//f.open().ok("oops").what(); // compile error, Open cannot be Debugged | |
//let u = Door{state: Unknown}; // compile error, not a DoorState | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment