Skip to content

Instantly share code, notes, and snippets.

@dcoles
Last active October 12, 2021 04:33
Show Gist options
  • Save dcoles/479e257643b946e9009ab116fda1fa44 to your computer and use it in GitHub Desktop.
Save dcoles/479e257643b946e9009ab116fda1fa44 to your computer and use it in GitHub Desktop.
Dynamic Finite-State-Machine in Rust
use std::fmt::Debug;
pub trait State: Debug {
fn execute(&self) -> Transition;
}
pub trait TransitionTo<S: State + 'static>: State {
fn transition_to(&self, to: &'static S) -> Transition {
Transition { to }
}
}
pub struct Transition {
to: &'static dyn State,
}
impl Transition {
pub fn to(&self) -> &'static dyn State {
self.to
}
}
mod fsm;
use std::time::Duration;
use crate::fsm::{State, TransitionTo, Transition};
#[derive(Debug)]
struct StateA;
#[derive(Debug)]
struct StateB;
impl State for StateA {
fn execute(&self) -> Transition {
self.transition_to(&StateB)
}
}
impl TransitionTo<StateB> for StateA {}
impl State for StateB {
fn execute(&self) -> Transition {
self.transition_to(&StateA)
}
}
impl TransitionTo<StateA> for StateB {}
fn main() {
let mut state: &dyn State = &StateA;
loop {
println!("{:?}", state);
std::thread::sleep(Duration::from_secs(1));
let transition = state.execute();
state = transition.to();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment