Skip to content

Instantly share code, notes, and snippets.

@kyleheadley
Created July 5, 2017 22:39
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 kyleheadley/f4073eef29d56ef67e6b1a489c3a7d47 to your computer and use it in GitHub Desktop.
Save kyleheadley/f4073eef29d56ef67e6b1a489c3a7d47 to your computer and use it in GitHub Desktop.
FSM example in rust
#![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