Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.